1

I have a URL fragment like 'users/123/edit' and I would like to match the first part of the string (in this case 'users'). The URL fragment could also be just 'users' and it should also match 'users'.

I could do it via JS find() and substr(), but I would like to see, how I do it via a Regular Expression. An explanation to the solution would be nice aswell.

Cœur
  • 37,241
  • 25
  • 195
  • 267
johnny
  • 8,696
  • 6
  • 25
  • 36

3 Answers3

2

Regex: /([a-z0-9]+)(\/[a-z0-9]+)*/i

Matches:

  1. users/123/edit

  2. users

  3. myuser123 // tell if not required

Explanation:

([a-z0-9]+) catches one or more occurrences (+) of [a-z0-9] and captures it.

(\/[a-z0-9]+)* catches zero or more occurrences (*) of / followed by [a-z0-9] and captures the last occurrence.

The ignore case flag makes the entire match case-insensitive.

DEMO

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
1

You can use split('/')[0]:

s = 'users/123/edit'.split('/')[0];
// users

OR else:

s = 'users'.split('/')[0];
// users
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

using regex :

str.match(/[^\/]*/i)[0]

this matches all characters different then (before) "/"

FIDDLE

radia
  • 1,456
  • 1
  • 13
  • 18