Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex, word not followed and not preceded by specific char

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

like image 655
MirrorMirror Avatar asked Dec 24 '12 08:12

MirrorMirror


2 Answers

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.

like image 61
Michael Avatar answered Sep 27 '22 16:09

Michael


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

like image 37
Rohit Jain Avatar answered Sep 27 '22 16:09

Rohit Jain