Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript jquery

Replacing substrings that aren't substrings of specific tags

发布于 2020-03-27 10:15:30

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?

Questioner
Leon Csergity
Viewed
176
Naga Sai A 2019-07-03 21:13

To achieve expected result, use below of splitting string by keyword test

  1. Split string by word- 'test'
  2. Check for characters '' and ''
  3. Update span with word test accordingly

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