Insert text before and after the selection in a textarea with JavaScript

javascript

Solution

Try the following:

var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";

If you want to search and replace, then the following code will do the trick (in non-Internet Explorer browsers):

var textBeforeSelection = yourTextarea.value.substr(0, yourTextarea.selectionStart);
var textAfterSelection = yourTextarea.value.substr(yourTextarea.selectionEnd, yourTextarea.value.length);
yourTextarea.value = textBeforeSelection + " new selection text " + textAfterSelection;

Problem

How can I insert text before and after the selection in a textarea with JavaScript? Selection occurs into a textarea field of an HTML form.

Original source