Peter Samyn
Peter Samyn

Reputation: 156

Javascript regular expression match URL up to a '/'

I am very new to regular expressions and have been trying to match URLs for an app using javascript.

I want to match something like this:

/some/url/string/(name)

but there are other URLs that use this same string but continue

/some/url/string/(name)/some/more

and I don't want to match those.

I thought I would need to use '[^/]' or '(?!/)' to match the (name) field without any following '/' but I have not had success with this.

Currently I use this:

'/some/url/string/\\S*'

But this matches the longer URLs that I don't want to match

Upvotes: 0

Views: 179

Answers (3)

ravi
ravi

Reputation: 7

try this:

/some/url/string/[a-z]+

Upvotes: -1

Jonathan Lam
Jonathan Lam

Reputation: 17351

EDIT Code is updated to answer question better, see comments below.

You're so close. You just need to add the + quantifier. Your first attempt (using [^/]) only went to look for the single next character, not multiple characters until the slash.

\/some\/url\/string\/[^\/]+$

(I added backslashes (\) to escape the forward slashes (/)).

See working example at Regex101.com.

Upvotes: 2

Javier Conde
Javier Conde

Reputation: 2593

You don't need a regular expresion to achieve it, you can try this: string.split('/')[4];

If you are looking for the full path, you can use: string.split('/').slice(0,5).join('/');

Upvotes: 1

Related Questions