0

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?

3 Answers 3

3

Better to use split I think:

'/foo/bar/'.split('/').filter(Boolean)
//=> ["foo", "bar"]

To get 1st element:

'/foo/bar/'.split('/').filter(Boolean)[0]
//=> "foo"
Sign up to request clarification or add additional context in comments.

2 Comments

not so much better, but thanks for the .filter(Boolean) suggestion - that's really neat one
@alex: Better in the sense that it avoid use of regex.
1

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.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.