Pytan
Pytan

Reputation: 1664

regex match to detect url pathname

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?

Upvotes: 1

Views: 228

Answers (1)

lemon
lemon

Reputation: 15482

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.

Upvotes: 2

Related Questions