如何使用 JavaScript 重建字符串

How to rebuild a string with JavaScript

本文关键字:字符串 重建 JavaScript 何使用      更新时间:2023-09-26

下面的代码现在可以工作了。感谢Matt-SL指出 子字符串和子字符串之间的区别

此函数用于在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(),并且不再从textEdit.selectionEnd中减去aftString.length。这意味着文本选择索引与substring()函数的预期参数一致。

下面是一个要演示的 JSFiddle。

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

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

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

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