0

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?

8
  • See the following for some better ways to get started with parsing html, then you can target just text nodes with your replacement, etc. stackoverflow.com/questions/10585029/… Commented Jul 2, 2019 at 20:15
  • You probably should investigate the TreeWalker API. Commented Jul 2, 2019 at 20:23
  • @ScottSauyet I don't think I'll be able to use that API the HTML isn't in the DOM. I have to parse it before it gets injected into it. But I was thinking around the same lines. Using JQuery I can parse the string into a JQuery<HTMLElement> or something like that. That has that structure. And I was thinking of traversing it to replace the strings where I need to. And not replacing it in the child nodes elements where I don't need to. Commented Jul 2, 2019 at 20:43
  • please share input string and expected output Commented Jul 2, 2019 at 20:51
  • @NagaSaiA if I have for example <div> test <a> test </a> </div> I would like to get <div> <span>test</span> <a> test </a> </div> where the text "test" wasn't switched out inside of <a> tag Commented Jul 2, 2019 at 20:55

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.