0

I have to match a string that is not inside tags. I am working on projects that I don't have control over the back-end html rendering code. What I need to do is add a hover functionality for multiple dynamic words. I created a script that will look for those key words in specific elements and add their description in title tags for the hover. My problem is that if other keywords are found in other keyword's title tags.

My JS:

var str = 'match <span title="not match here">match</span> match'; str.replace( /match/gim, 'ok' ); 

I do not want the "match" word in the title attribute to be replaced, my desired result is:

'ok <span title="not match here">ok</span> ok' 

how can I do that with Javascript?

I tried the expression below but it's not working for me:

^((?!(".+")match)*$ 
3
  • How about just parsing it as HTML instead, as that's what it is ? Commented Aug 1, 2014 at 3:04
  • @adeneo Thanks for your comment but I don't have control over the backend and what I'm asked to do is create a function that will look for dynamic strings and wrap them in a span with a title attribute containing the description. I edited the question to add more details. Commented Aug 1, 2014 at 3:15
  • Who cares about the backend, you should construct the functionality that wraps elements to be hovered in a such a way that it uses the browser to parse the HTML and then work with that, not strings and regex. Commented Aug 1, 2014 at 3:17

1 Answer 1

2

You need to capture tags first to be able to avoid them:

var result = str.replace(/(<[^>]*>)|match/gi, function (_,g1) { return (g1==undefined)? 'ok':g1; }); 

But if you can, using the DOM is probably the best way.

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

1 Comment

thanks, this worked for me, I did not know I could use functions on the second parameter, I'll look more into that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.