0

I need to write JS regex (or function) that tells me if a string is in that format:

/root/:param1/:param2/:param3/.../

OR

/root/:param1/:param2/:param3/... (without last slash)

Any ideas? Thanks.

Tal Levi
  • 321
  • 6
  • 19

1 Answers1

1

If I'm interpreting your question correctly, it looks like we can break this pattern down into three primary components:

  1. Start with /root
  2. Followed by some number of /:param
  3. Optionally followed by a /

Now we just need to develop the regular expressions for each component and combine them:

  1. Start with /root
    • Start of the string is marked by ^ and we follow with /root
    • ^/root
  2. Followed by some number of /:param:
    • Let's say :param should match 1-N characters (+ operator) that are not a forward slash [^/]
    • This gives us /[^/]+
    • 0-N of this entire unit can be matched using groups and the * operator: (/[^/]+)*
  3. Optionally followed by a /
    • Use the ? operator: /?
    • Append a $ to specify the string's end

All together we get the regular expression ^/root(/[^/]+)*/?$. You can use RegExp.prototype.test to check for matches:

r = new RegExp('^/root(/[^/]+)*/?$')
r.test('/root')                         // => true
r.test('/root/')                        // => true
r.test('/root/apple/banana')            // => true
r.test('/root/zebra/monkey/golf-cart/') // => true

If you're looking to match a URL path segment you'll need to use a more specific character set instead of the [^/] I used here for :param characters.

Community
  • 1
  • 1
fny
  • 31,255
  • 16
  • 96
  • 127