Nathan Osman
Nathan Osman

Reputation: 73175

How come this RegExp doesn't work when passed in as a string?

Chrome 9.0.597.83 beta on Ubuntu 10.10:

enter image description here

As you can see, the pattern doesn't work when passed in as a string, but works fine when passed in as a RegExp object. Why is this? I need to be able to pass it in as a string so that I can manipulate it before performing the match.


Note: I just posted a question very similar to this... and thought I was doing something wrong and deleted the question. Then when I tried something slightly different, I got the problem again.

Upvotes: 1

Views: 95

Answers (1)

lonesomeday
lonesomeday

Reputation: 237845

The problem is with the backslash \. This is escaping the W character. In a string, \W evaluates to W. You need to escape the backslash:

"e c".match(new RegExp('(?:^|\\W)c(?:\\W|$)'))

Upvotes: 5

Related Questions