I need to replace key words in the HTML and put a span around them that later will catch a click event.
I get the HTML in string format, and what I tried was to use regular expressions to replace the specific string with the string surrounded by the span. And this all works fine, but the problem is it matches with links and other tags. so it surrounds parts of those too if the key word matches in them.
Code that I used to replace the keywords:
textToBeChanged = textToBeChanged.replace(new RegExp(keyword, 'ig'), keywordWrappedInSpan)
Is there a way to expand this so that if its in a link or other tag it does not replace it? Or maybe some way with JQuery?
To achieve expected result, use below of splitting string by keyword test
working code example
var str = '<div> test <a> test </a> </div>'
console.log(str.split('test').map(v => {
if(v.indexOf('<a>') === -1 && v.indexOf('</a>') === -1){
v = v + '<span>test</span>'
}else{
if(v.indexOf('<a>') !== -1){
v = v + 'test'
}
}
return v
}).join(''))
codepen - https://codepen.io/nagasai/pen/rEvvGV?editors=1010
Really interesting solution. Sorry for the super late reply though. I could not get around to that part of the application, so only now will I be able to try applying this