javascriptregexurl-fragment

Looking for regular expression that matches the first part of a URL fragment


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.


Solution

  • using regex :

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

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

    FIDDLE