JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Select <span id="selected">this</span>, then click <button id="click">here</button>.</h1>
<div id="thetext" contenteditable="true">
<p>Hi this is Mr This</p>
<p>So here is some text. This is the text we're hoping to effect. The idea is that all the this get replaced with underlined css. watch this space.</p>
<p>Lots of love</p>
<p>Mr this</p>
<p>[email protected]</p>
</div>
CSS
#selected {background-color:yellow; padding:0 3px;}
#click {text-decoration:underline;}
#click:hover {cursor:pointer;}
#thetext {margin-top:20px;}
.gotit {background-color:red; padding:0 3px;}
.regit {background-color:blue; padding:0 3px;}
JavaScript
if(!window.Kolich){Kolich = {};}
Kolich.Selector = {};
Kolich.Selector.getSelected = function(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;
}
Kolich.Selector.click = function(){
var st = Kolich.Selector.getSelected();
if(st!=''){
/* ############ HERES THE PROBLEM ############ */
/* #### #### */
/* #### This only selects first instance #### */
/* ####-----------------------------------#### */
text = $("#thetext").html();
text = text.replace(st, '<span class="gotit">'+st+'</span>');
$("#thetext").html(text);
/* ####-----------------------------------#### */
/* #### Should use regex to select all #### */
/* ####-----------------------------------#### */
regSt = '/'+st+'/g';
text = $("#thetext").html();
text = text.replace(regSt, '<span class="regit">'+st+'</span>');
$("#thetext").html(text);
/* ####-----------------------------------#### */
/* #### #### */
/* ################ THANKS ! ################# */
}
}
$(document).ready(function(){
$("#click").click(Kolich.Selector.click);
});