简体   繁体   English

使用javascript删除部分文字

[英]Remove a portion of text using javascript

Here's the code: 这是代码:

 function bold() { var text = document.getElementById("post-body"); var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart); var text = '**'; $('#post-body').val(function(_, val) { return val + text + t + text; }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea name="post-body" id="post-body" rows="20" style="margin-left: 0px; margin-right: 0px; width: 400px;"></textarea> <div> <button id="bold" value="**" onclick="bold()">B</button> </div> 

What I am trying to do is similar to how comments on Stack Overflow work: you highlight text in the text box, and click a button. 我正在尝试做的事情类似于对Stack Overflow的评论工作:在文本框中突出显示文本,然后单击一个按钮。 The button then appends and prepends the proper syntax to the text. 然后,该按钮将适当的语法附加并添加到文本中。 I am able to apply the proper syntax, but the highlighted text is duplicated. 我能够应用正确的语法,但是突出显示的文本是重复的。

I know it's because in my code, I have 我知道这是因为在我的代码中

return val + text + t + text; 

where val is all of the text in the textarea, and t is the highlighted text, but I'm not sure how to remove the highlighted text from val and add the new version in the form of t . 其中val是文本区域中的所有文本, t是突出显示的文本,但是我不确定如何从val删除突出显示的文本并以t的形式添加新版本。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You can record the text before and after and then return the text before, the selection and the text after. 您可以记录之前和之后的文本,然后返回之前的文本,选择内容和之后的文本。

 function bold() { var text = document.getElementById("post-body"); var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart); var before = text.value.slice(0, text.selectionStart); var after = text.value.slice(text.selectionEnd); var text = '**'; $('#post-body').val(function(_, val) { return before + text + t + text + after; }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea name="post-body" id="post-body" rows="20" style="margin-left: 0px; margin-right: 0px; width: 400px;">Select some text here.</textarea> <div> <button id="bold" value="**" onclick="bold()">B</button> </div> 

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

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