JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" id="insertButton" value="Surround selected text">
<br>
<textarea id="texteditor" rows="5" cols="50">Place the caret or select some text in here and press the button</textarea>
JavaScript
function addTag(prefix, suffix) {
var texteditor = document.getElementById("texteditor");
var val = texteditor.value;
var start = texteditor.selectionStart;
var end = texteditor.selectionEnd;
// Insert the prefix and suffix
texteditor.value = val.slice(0, start) +
'[' + prefix + ']' + val.slice(start, end) + '[' + suffix + ']' +
val.slice(end);
// Reset the selection
texteditor.selectionStart = start + prefix.length + 2;
texteditor.selectionEnd = texteditor.selectionStart + (end - start);
}
document.getElementById("insertButton").onmousedown = function() {
document.getElementById("texteditor").focus();
addTag("b", "/b");
return false;
};