I'm trying to make a router in Nodejs. A big part of that is URI -> action
, so I'll need an easy configurable list of URI's and regexping them to regexps to match against the request URI.
Simple! I've done this in PHP a million times. Give or take.
So this is what I do (to test):
> uri = '/users/#/status/*'
> uri.replace(/\//g, '\\/').replace(/#/g, '(\d+)').r开发者_如何转开发eplace(/\*/g, '([^/]+)')
What I'm doing is 1) escaping /
and 2) replacing #
with a \d+
and 3) replacing *
with a [^/]+
In Chrome this works as expected:
< \/users\/(d+)\/status\/([^/]+)
Escaped /
and replaced #
and *
correctly. This is V8.
In Nodejs:
< \\/users\\/(d+)\\/status\\/([^/]+)
Que!? Every /
is doubly escaped? I either get a doubly escaped /
or a not escaped /
.
The regex is right, right?
I'm using Chrome 15 dev (V8 javascript) and Node 0.5.8 dev (V8 javascript). What's going on here?
Potentially interesting
If I test/^\/users\/(\d+)\/status\/([^/]+)/.test('/users/1/status/x')
it returns true in both Chrome and Node.This is due to a difference in the way the Node REPL differs from the Chrome console. When you run the command in Node, you're getting a peek at the escaped string (including the "invisible" escape characters), but when you see it in Chrome, it's the actual string evaluated, with the escape characters removed. They're the same strings, but Chrome is trying to "prettify" it for you.
In fact, if you copy and paste the string you got from Node into the Chrome (or even a FF Firebug) console, you'll get a string with the single escapes. If you copy and paste it in again, it'll remove the next level of escapes characters.
Chrome console:
> "\\/users\\/(d+)\\/status\\/([^/]+)"
"\/users\/(d+)\/status\/([^/]+)"
> "\/users\/(d+)\/status\/([^/]+)"
"/users/(d+)/status/([^/]+)"
精彩评论