JSFiddle - React, Tailwind, and code Playground

by edwardsharp

HTML

<input type="button" id="surroundButton" value="Surround" unselectable="on">
<div contenteditable="true" id="editor">Select some text in here and press the button to surround it in BBCode</div>

JavaScript

function surroundSelection(textBefore, textAfter) {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount > 0) {
            var range = sel.getRangeAt(0);
            var startNode = range.startContainer, startOffset = range.startOffset;
            var boundaryRange = range.cloneRange();
            var startTextNode = document.createTextNode(textBefore);
            var endTextNode = document.createTextNode(textAfter);
            boundaryRange.collapse(false);
            boundaryRange.insertNode(endTextNode);
            boundaryRange.setStart(startNode, startOffset);
            boundaryRange.collapse(true);
            boundaryRange.insertNode(startTextNode);
            
            // Reselect the original text
            range.setStartAfter(startTextNode);
            range.setEndBefore(endTextNode);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

function surroundSelectionInBbcode(tagName) {
    surroundSelection("[" + tagName + "]", "[/" + tagName + "]");
}

document.getElementById("surroundButton").onclick = function() {
    document.getElementById("editor").focus();
    surroundSelectionInBbcode("b");
    return false;
};