javascript regex, word not followed and not preced

2020-06-04 02:23发布

I guess I'm not very good at regular expressions, so here is my problem (I'm sure it's easy to solve, but somehow I can't seem to find how )

var word = "aaa";
text = text.replace( new RegExp(word, "g"),
                     "<span style='background-color: yellow'>"+word+"</span>");

this is working in most cases.

What I want to do is for the regex ONLY TO WORK when word is not followed by the char / and not preceded with char ".

2条回答
霸刀☆藐视天下
2楼-- · 2020-06-04 02:51

You can use this regex: -

'([^"])' + word + '(?!/)'

and replace it with - "$1g"

Note that Javascript does not support look-behinds. So, you need to capture the previous character and ensure that it is not ", using negated character class.

See demo at http://fiddle.re/zdjt

查看更多
别忘想泡老子
3楼-- · 2020-06-04 02:53

You're going to want to use a negative look-ahead.

Regex: '[^"]' + word + '(?!/)'

Edit: While it doesn't matter as it appears you already found your answer by avoiding look-behinds, Rohit noticed something I didn't. You're going to need to capture the [^\"] and include it in the replace so that it does not get discarded. This wasn't necessary for the look-head since look-arounds by definition aren't included in captures.

查看更多
登录 后发表回答