繁体   English   中英

如何使用JavaScript重建字符串

[英]How to rebuild a string with JavaScript

以下代码现在正在运行。 感谢Matt-SL,他指出了substr和substring之间的区别

此功能用于在文本区域中为textarea添加标签,就像您在Stackoverflow上的问题和答案中将文本以粗体显示一样。

 var lastFocus; $("#bold").click(function (e) { e.preventDefault(); e.stopPropagation(); befString = "<b>"; aftString = "</b>"; dif = aftString.length - befString.length; if (lastFocus) { setTimeout(function () { lastFocus.focus() }, 10); var textEdit = document.getElementById('textEdit'); var befSel = textEdit.value.substr(0, textEdit.selectionStart); var aftSel = textEdit.value.substr(textEdit.selectionEnd, textEdit.length); var select = textEdit.value.substr(textEdit.selectionStart, textEdit.selectionEnd-aftString.length ); textEdit.value = befSel + befString + select + aftString + aftSel; } return (false); }); $("#textEdit").blur(function() { lastFocus = this; }); 
 #textEdit{ width:300px; height:200px; } #bold{ font-size:25px; cursor:pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="editToolBar" class="editToolBar"> Select all 2's and <span id="bold"></b>click here</b></span> </div> <textarea id="textEdit" type="text" name="textEdit" size="" class="editDocInput" data-type="" >111112222233333</textarea> 
我的问题:

我无法弄清楚为什么字符串没有正确地重新组合在一起。 试一试,亲眼看看。

更改您在其中定义行var select使用substring()代替substr()和不再减去aftString.lengthtextEdit.selectionEnd 这意味着文本选择索引与substring()函数的预期参数对齐。

这是一个JSFiddle来演示。

var select = textEdit.value.substring(textEdit.selectionStart, textEdit.selectionEnd);

根据selectionEnd的文档 ,它是选择的第一个字符的索引。

substrsubstring之间的区别是他们期望的第二个参数:

  • substr(startIndex, length)
  • substring(startIndex, endIndex)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM