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.
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.
If I'm interpreting your question correctly, it looks like we can break this pattern down into three primary components:
/root
/:param
/
Now we just need to develop the regular expressions for each component and combine them:
/root
^
and we follow with /root
^/root
/:param
:
:param
should match 1-N characters (+
operator) that are not a forward slash [^/]
/[^/]+
*
operator: (/[^/]+)*
/
?
operator: /?
$
to specify the string's endAll 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.