Haroen Viaene Haroen Viaene - 3 months ago 9
Javascript Question

Wrap text not part of a tag in a tag

I'm trying to highlight (with

<mark
) a search string inside another string, but it shouldn't be part of a tag (i.e.
te
in
<cite>
shouldn't match, but
te
in
test
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)(.*([^<>]*?<.+?>)?)
    (
    .replace
    gives undefined's)



Example:

String to wrap:
te


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

Regex:

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

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

Live demo

Comments