Home > Software design >  regex match to detect url pathname
regex match to detect url pathname

Time:08-03

I want to detect if given string is a pathname or not in typescript

For example, the followings are valid pathnames

/
/abc
/abc/def
/abc/def/
/abc/def/ghj

But these are not valid

///
/abc//
abc
abc/

So far, I have ^\/\w but it doesnt work for all cases. How can I improve it?

CodePudding user response:

You can use the following regex:

^\/(\w \/)*\w*$

which attempts to match:

  • \/: a slash
  • (\w \/)*: multiple combinations of alphanumerical characters slash (even zero)
  • \w*: an optional combination of alphanumerical characters

between start of string ^ and end of string $.

Check the demo here.

  • Related