How to properly locate all the keywords in a string that may have overlapped to each other.
I have a sentence:
“Play around with the code and click on the Run button to view the result.”
And two keyword sets.
keywordSet1 = ['click on the Run', 'view the result']
keywordSet2 = ['on the', 'code and click on', 'the Run button to', 'Play around']
Apparently,
'click on the Run' in set 1 is partially overlapped with 'code and click on', 'the Run button to' in set 2;
'on the' in set 2 is overlapped with 'click on the Run' in set 1
To locate all keywords position, I write this code. To surround all keywords with by $#k1{keyword}$ or $#k2{keyword}$
text = “Play around with the code and click on the Run button to view the result.”
keywordSet1.forEach((key) => {text = text.replace(key,`$#k1$&$`)})
keywordSet2.forEach((key) => {text = text.replace(key,`$#k2$&$`)})
Problem:
However, this way sometimes will ease the marking of k1 in the sentences, which causing a problem in rendering. For example, from the result of the replace method. It became this
'$#k2Play around$ with the code and $#k1click $#k2on the$ Run$ button to $#k1view the result$'
For example, in keyword set 1, 'click on the Run' is somehow overlapped with 'code and click on' , 'the Run button to' in keyword set 2.
But with my code, it somehow didnt work as my expected, highlighted part show the problem
'$#k2Play around$ with the code and $#k1click $#k2on the$ Run$ button to $#k1view the result$' ('on the' is only highlighted by $#k2on the$)
My expectation is:
'$#k2Play around$ with the $#k2code and$ $#k1click$ $k1#$#k2on the Run$$ $#k2button to$ $#k1view the result$'
To view it visually, here is an digram