Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a javascript regex to match a specific path

I need help to match a url that matches only if

  • the path matches exactly /gummybear/ or /gummybear (case sensetive)
  • the protocol is http or https
  • the domain/host/port/hash can be anything

the regex should not match if

  • the path is /gummybear/foobar
  • it contains search parameters such as ?query=string

So far i got this:

/^http[s]?:\/\/?[^\/\s]+\/gummybear[\/]?/

examples it should be true for

https://www.example.com:81/gummybear/
http://www.example.com/gummybear#top
https://example.com:81/gummybear#/foobar/?search=params
http://www.exa.mple.com:81/gummybear
https://example.com:81/gummybear/#/exaple/1234/

examples that it should be false for

https://www.example.com:81/foo/gummybear/
https://www.example.com:81/guMmybear/
https://www.example.com:81/gummybear.html
http://www.example.com/gummybear/apple#top
file://example.com:81/gummybear#/foobar/?search=params
http://www.exa.mple.com:81/gummybear?search=apple#lol
https://example.com:81/#/gummybear/
http://www.test.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=value#top
like image 891
Endless Avatar asked Dec 06 '25 01:12

Endless


1 Answers

For your specific needs, I can come up with this regex:

^https?://[^/]+/gummybear(?:/?|/?#.*)$

Regular expression visualization

Working demo

enter image description here

I haven't escaped slashes to make it more readable, but for javascript you can use:

^https?:\/\/[^\/]+\/gummybear(?:\/?|\/?#.*)$
like image 179
Federico Piazza Avatar answered Dec 08 '25 13:12

Federico Piazza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!