user689751
user689751

Reputation:

capture first part of the url

Let's say I've following URLs.

/product
/product/1
/product/1/buy

/customer
/customer/1
/customer1/contact

I'm trying for a regular expression to get the following match so I can run a switch statement on it.

/product

/customer

I've tried the following and trying other options as well.

request.url.match(/^\/(.*)(\/?)/)

Upvotes: 1

Views: 186

Answers (3)

BrTkCa
BrTkCa

Reputation: 4783

Another option is to use split:

var result = request.url.split("/")[1]; // result = product

Fiddle

Upvotes: 1

You were close! Try this one

/^\/(.*?)(\/|$)/

E.g.

/^\/(.*?)(\/|$)/.exec('/customer'); // ["/customer", "customer", ""]
/^\/(.*?)(\/|$)/.exec('/customer/asd'); // ["/customer/", "customer"]
/^\/(.*?)(\/|$)/.exec('/customer/asd/asd'); // ["/customer/", "customer", "/"]

Why
The ^\/ will match the start of the string.
The (.*?) will match anything after (including /, ? makes it non-greedy).
The final \/ will make the regex backtrack until / is found after the (.*?) or if the end of the string is found $.

Upvotes: 0

StardustGogeta
StardustGogeta

Reputation: 3406

arr = [
        '/product',
        '/product/1',
        '/product/1/buy',
        '/customer',
        '/customer/1',
        '/customer/1/contact'
      ]

arr.forEach(a=>console.log(a.match(/^\/([^\/]*)/g)[0]));

How about this solution?

Upvotes: 1

Related Questions