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 ".
You can use this regex: -
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
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.