This question builds on an answer provided in How to wrap word into span on user click in javascript.
In my example, the user can double-click on any word to wrap it in a span element, but b/c this is based on splitting on whitespace, it won't 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 punctuation detection for the split, but that would of course remove the punctuation, and I need to retain it, so using the following won't meet my needs:
html.split(/\s+|[.,-\/#!$%\^&\*;:{}=\-_`~()]/)
Fiddle: http://jsfiddle.net/b11nxk92/3/