JuJoDi
JuJoDi

Reputation: 14975

Javascript regex syntax error trying to match URL causes unexpected token ^

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

Answers (3)

xdazz
xdazz

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

anubhava
anubhava

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions