code

wrapping a selection in bbcode

a button wraps selected text in bbcode tags while keeping the original text selected.

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;
};

this demo preserves the compiled output and may depend on external libraries or services that are no longer available.

original jsfiddle post