Haroen Viaene Haroen Viaene - 11 months ago 40
Javascript Question

Wrap text not part of a tag in a tag

I'm trying to highlight (with

) a search string inside another string, but it shouldn't be part of a tag (i.e.
shouldn't match, but
should). I've been using code like this to replace the match with the second regex listed, but that only works nestted.

someElement.innerHTML.replace(regex, function(full, before, match, after) {
return before + '<mark>' + match + '</mark>' + after;

Suggestions I tried:

  • <\/\w*>(\w*\s*)*(te)(\w*\s*)*<([a-z]*\s*\w*="\w*")*>
    (doesn't match at all?)

  • (<.+?>[^<>]*?.*)(te)(.*[^<>]*?<.+?>)
    (only works on the nested tags)

  • ((<.+?>[^<>]*?)?.*)(te)(.*([^<>]*?<.+?>)?)
    gives undefined's)


String to wrap:

Input text:

‘This is a test string’
<cite> — some test wrapped too</cite>

Expected output:

‘This is a <mark>te</mark>st string’
<cite> — some <mark>te</mark>st wrapped too</cite>

I've browsed a lot of "duplicates", but couldn't find an exact one, but if someone can lead me to a working example, that'd be lovely too, thanks!

Answer Source


(te)(?![^<> ]*>)

It benefits from a negative lookahead to check if it is within an opening / closing tag or not.

Live demo