I have a div containing a string. For instance:
<div id='original'>A red chair that is on the left of another chair next to the door</div>
I have stored some user-selected substrings in the db with start and end indices. For example:
phrase: chair, start: 43, end: 48
phrase: the door, start: 58, end: 66
Now, I'd like to add a span or a div around the above two phrases in the 'original' div so that I can highlight these phrases.
Expected result:
<div id='original'>A red chair that is on the left of another <div style="display:inline; color:#ed3833; cursor:pointer;">chair</div> next to <div style="display:inline; color:#ed3833; cursor:pointer;">the door</div></div>
For one phrase, I'm able to insert div around it using the start and end index but for the subsequent inserts, it obviously fails because the index has now changed due to the addition of div around the first phrase. Could you please help me with this?
I don't know if it helps but for for the adding div around first phrase, I'm using the following logic:
str = $('#original').text()
var preStr = str.substring(0, startIdx);
var newStr = `<div style="display:inline; color:#ed3833; cursor:pointer;">${phrase}</div>`
var postStr = str.substring(endIdx, str.length);
result = preStr+newStr+postStr;
Let me know if you need more clarity I will try and explain a bit better.
You can form arrays for indices and do that like this :