Reputation: 5770
I'm checking for a very specific pattern in URLs so that a set of code is only executed on the correct type of page. Currently, I've got something like:
/^http:\/\/www\.example\.com\/(?:example\/[^\/]+\/?)?$/;
So, it'll return true
for example.com
and example.com/example/anythinghere/
. However, sometimes this website will append arguments such as ?postCount=25
or something to the end of the URL, so you get:
example.com/example/anythinghere/?postCount=25
Because of this, if I throw the current expression into a conditional, it will return false should there be URL arguments. How would I best go about changing the regex expression to allow for an optional URL argument wildcard, so that, if there's a question mark followed by any additional information, it will always return true, and, if it's omitted, it will still return true?
It would need to return true for:
http://www.example.com/?argumentshere
and
http://www.example.com/example/anythinghere/?argumentshere
As well as those same URLs without the extra arguments.
Upvotes: 0
Views: 232
Reputation: 70460
Upgrading my comment to an answer:
/^http:\/\/www\.example\.com\/(?:example\/[^\/]+\/?)?$/;
Meanse:
/^ # start of string
http:\/\/www\.example\.com\/ #literal http://www.example.com/
(?:
example\/[^\/]+\/? #followed by example/whatever (optionally closed by /)
)?
$ end-of-string
/
The main problem here, is your requirements ("followed by an optional querystring") does not match you regex (which requires an end-of-string). We solve it by:
/^ # start of string
http:\/\/www\.example\.com\/ #literal http://www.example.com/
(?:
example\/[^\/]+\/? #followed by example/whatever (optionally closed by /)
)?
(\?|$) followed by either an end-of-string (original), or a literal `?` (which in url context means the rest is a query string and not a path anymore).
/
Upvotes: 0
Reputation: 11703
Try following regex:
^http:\/\/www\.example\.com(?:\/example\/[^\/]+\/?)?\??.*$
Upvotes: 1
Reputation: 3435
You can build the URL without parameters and compare that with your current expression.
location.protocol + '//' + location.host + location.pathname
How to get the URL without any parameters in JavaScript?
Upvotes: 0