Garrett Massey Garrett Massey - 4 years ago 91
Javascript Question

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. 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
.

Any help would be greatly appreciated.

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download