简体   繁体   English

如何使用JavaScript重建字符串

[英]How to rebuild a string with JavaScript

This code below is now working. 以下代码现在正在运行。 Credit to Matt-SL who pointed out the difference between substr and substring 感谢Matt-SL,他指出了substr和substring之间的区别

This function serve to add tags to the text in a textarea just like the one you use to put your text in bold in your question&answer on Stackoverflow. 此功能用于在文本区域中为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> 
My problem: 我的问题:

I can't figure out why the string is not being put back together properly. 我无法弄清楚为什么字符串没有正确地重新组合在一起。 Try it and see for you self. 试一试,亲眼看看。

Change the line in which you define var select to use substring() instead of substr() , and no longer subtract aftString.length from textEdit.selectionEnd . 更改您在其中定义行var select使用substring()代替substr()和不再减去aftString.lengthtextEdit.selectionEnd This means the text selection indices line up with the expected parameters of the substring() function. 这意味着文本选择索引与substring()函数的预期参数对齐。

Here is a JSFiddle to demonstrate. 这是一个JSFiddle来演示。

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

As per the documentation for selectionEnd , it is the index of the first character after the selection. 根据selectionEnd的文档 ,它是选择的第一个字符的索引。

The difference between substr and substring is what they expect as their second parameter: substrsubstring之间的区别是他们期望的第二个参数:

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

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

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