Reputation: 14975
I'm trying to capture the text in between /
s in a URL in Javascript. In the Regex tester I can successfully do that using
[^/]*
and when passed something like
/foo/bar/
it returns foo
and bar
as matches (which is what I want). In my javascript (node.js?) I am trying to use this regex as
var match = req.url.match ([^/]*);
but I get the error
SyntaxError: Unexpected token ^
How to I capture this regex in Javascript?
Upvotes: 0
Views: 1128
Reputation: 160833
You need delimiters for the regex literal, also with the g
(global) modifier:
var match = req.url.match(/[^/]+/g);
Change *
to +
to avoid matching empty strings.
Upvotes: 1
Reputation: 785126
Better to use split
I think:
'/foo/bar/'.split('/').filter(Boolean)
//=> ["foo", "bar"]
To get 1st element:
'/foo/bar/'.split('/').filter(Boolean)[0]
//=> "foo"
Upvotes: 3
Reputation: 324640
You forgot the slashes that make a regex literal:
var match = req.url.match(/[^\/]*/g);
Note that you need to escape the slash in your regex!
Upvotes: 1