views:

43

answers:

2

I have html code as a string variable

like a = "<span> Spain will win ....... </span>"

and I want to heightlight "spa" in the String.

I have to use RegExp, How should I write the pattern that it ignores the "spa" on span tag, but highlight in Spain.

Thanks

+6  A: 

JavaScript doesn't support lookbehind, so you're a bit limited, but this should work:

\bSpa(?!n[^>]*>)

Explanation:

\b: Assert that the match starts at a word boundary.

Spa: Match Spa.

(?!...): Assert that it is impossible to match the following:

n: An n, followed by...

[^>]*: zero or more non-> characters, followed by...

>: a >.

Tim Pietzcker
@Gert G: [quote]and I want to heightlight "spa" in the String.[/quote]
jigfox
+1  A: 

You can try this:

var s = "<span> Spain will win ....... </span>Spaniel";
s.replace(/(spa(?!n[^>]*>))/ig,'<span class="highlight">\$1</span>')
jigfox
@Gert G: Yes I tried! I didn't highlight Spain, but that wasn't asked for, it should highlight only the "spa" of "spain", but not the "spa" from "<span>". the resulting string:"<span> <span class="highlight">Spa</span>in will win ....... </span><span class="highlight">Spa</span>niel"
jigfox