the javascript string.replace method actually takes a RegExp as it's first argument. Without specifying it as 'greedy' it will only match the first.
Ordinary regex in javascript would look like
/expression/g
, the g stands for greedy. As you are creating one from a string, just use the RegExp constructor like this:
function makeBold(){
var highlight = window.getSelection();
var span = '<span style="font-weight:bold;">' + highlight + '</span>';
document.body.innerHTML = document.body.innerHTML.replace(new RegExp(highlight , 'g'), span);
}
EDIT: now I have read the question again >_<
function makeBold(){
var span = '<span style="font-weight:bold;">' + highlight + '</span>';
var selected, range;
if (window.getSelection) {
selected= window.getSelection();
if (selected.rangeCount) {
range = selected.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(span));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = span;
}
}
EDIT2: and now the version that inserts html (i hope)
function getSelectionHtml() {
var sel, range, node;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
var html = '<span style="font-weight:bold;">' + range + '</span>'
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.collapse(false);
range.pasteHTML(html);
}
}
Now this one I HAVE tested:
https://jsfiddle.net/dKaJ3/1261/[
^]