开发者

RegularExpression String replace

开发者 https://www.devze.com 2023-01-06 00:08 出处:网络
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 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


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 >.


You can try this:

var s = "<span> Spain will win ....... </span>Spaniel";
s.replace(/(spa(?!n[^>]*>))/ig,'<span class="highlight">\$1</span>')
0

精彩评论

暂无评论...
验证码 换一张
取 消