How come this RegExp doesn't work when passed in as a string?
Chrome 9.0.597.83 beta on Ubuntu 10.10:
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 thou开发者_Python百科ght I was doing something wrong and deleted the question. Then when I tried something slightly different, I got the problem again.
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|$)'))
精彩评论