swaggyP
swaggyP

Reputation: 365

javascript regular expression to match url

I am trying to match a URL that starts with /user/ and ends with any number and slash.

example:

/user/345/

I tried /user/\d{3}, but the interpreter gives me an error at \d.

if (request.url == '/') {
    absPath = './public/index.html';
    serveStatic(response, cache, absPath);
} else if (request.url.match(/user/\d{3})) {}

any suggestions?

Upvotes: 0

Views: 81

Answers (3)

Ωmega
Ωmega

Reputation: 43673

Let's make trailing slash optional:

/\/user\/\d{3}\/?/

or

/\/user\/[0-9]{3}\/?/

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53525

Try this:

var str = "/user/345/";
alert(str.match(/\/user\/\d+\//g) != null);

without the last slash:

alert(str.match(/\/user\/\d+/g) != null);

Upvotes: 1

Nick
Nick

Reputation: 4092

You're missing a backslash

request.url.match("/user/\\d{3}")

Upvotes: 0

Related Questions