简体   繁体   中英

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

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.

 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 . This means the text selection indices line up with the expected parameters of the substring() function.

Here is a JSFiddle to demonstrate.

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.

The difference between substr and substring is what they expect as their second parameter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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