I am trying to wrap every occurrence of the word "example" with <a href="#" class="highlight"></a>
. I know I will need to do this via RegExp
, and I've had similar versions working. However I also want to check and see if the occurence is already wrapped in an <span>
. And if so, to ignore that one.
HTML:
<span>This</span>
<span>Example</span>.
<div> Here is my example text. I will be looking to highlight the word <span class="blue-underline">example.</span> </div>
</body>
JS:
let target = 'example';
var text = document.querySelector('body').textContent;
var regex = new RegExp('(' + target + ')', 'ig');
const newtext = text.replace(regex, '<a href="#" class="highlight">$1</a>');
text.innerHTML = newtext;
Here is my JSFiddle as well.
Is there a way to programmatically accomplish that?