7

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

MirrorMirror
  • 717
  • 8
  • 32
  • 65

2 Answers2

14

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.

Daniel Foust
  • 584
  • 1
  • 5
  • 24
Michael
  • 3,208
  • 18
  • 27
3

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

Rohit Jain
  • 195,192
  • 43
  • 369
  • 489
  • This fails if the match is at beginning or end of line. Perhaps the question could mention whether this matters. – tripleee Dec 24 '12 at 09:02