This question is based on the answer provided in How to wrap a word in a range on a user click in javascript .
In my example, the user can double-click on any word to wrap it in a span, but b / c is based on space breaks, it will not work if the word is followed by punctuation.
HTML:
<div class="color-coding">
<span class="orange color-coding">Hello world this is some text.</span>
<br>
<span class="orange color-coding">Here is some more!</span>
</div>
JS:
jQuery(document).ready(function($) {
$('.color-coding').dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var sword = $.trim(range.toString());
if(sword.length)
{
var newWord = "<span class='highlight'>"+sword+"</span>";
$(this).each(function(){
$(this).html(function( _, html ) {
return html.split(/\s+/).map(function( word ) {
return word === sword ? newWord : word;
}).join(' ');
});
});
}
range.collapse();
e.stopPropagation();
});
});
I could add the detection of punctuation for separation, but this of course will remove the punctuation, and I need to save it, so using the following will not meet my needs:
html.split(/\s+|[.,-\/
Fiddle: http://jsfiddle.net/b11nxk92/3/