Home > Enterprise >  how to match 3 possible options in url path using regex in react?
how to match 3 possible options in url path using regex in react?

Time:07-27

/home/(a|b|c)/resource

Esstentially, the above is what I trying to match in my route. The middle slot can be either a, b, or c.

CodePudding user response:

First we improve the RE to /^\/home\/(a|b|c)\/resource$/ then use test method

/^\/home\/(a|b|c)\/resource$/.test('/home/a/resource') // will true
/^\/home\/(a|b|c)\/resource$/.test('/home/other-path/resource') // will false

CodePudding user response:

As of why the regex is /^\/home\/(a|b|c)\/resource$/ based on @elVengador answer is because you have to escape the forward slash by using a backslash in order to match it - \/. And, the caret means the start of the string and $ means end of the string.

  • Related