Hi I'm trying to match a specific URL that allows for query strings. Basically I need the following to happen:
http://some.test.domain.com
- Passhttp://some.test.domain.com/
- Passhttp://some.test.domain.com/home
- Passhttp://some.test.domain.com/?id=999
- Passhttp://some.test.domain.com/home?id=888&rt=000
- Passhttp://some.test.domain.com/other
- Failhttp://some.test.domain.com/another?id=999
- FailHere is what I have so far:
var pattern = new RegExp('^(https?:\/\/some\.test\.domain\.com(\/{0,1}|\/home{0,1}))$');
if (pattern.test(window.location.href)){
console.log('yes');
}
The above code only works for the first three and not for the query strings. Any help would be appreciated. Thanks.
Use Regex to check a given URLcharacter and querystring name/value pair. If yes, the URL definitely contains a query string and vice versa. You can see live version of this approach here by clicking on the “Run Example” button.
pathname. The pathname property of the URL interface is a string containing an initial / followed by the path of the URL, not including the query string or fragment (or the empty string if there is no path).
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
A pattern like this should work (at least for your specific domain)
/^http:\/\/some\.test\.domain\.com(\/(home)?(\?.*)?)?$/
This will match a literal http://some.test.domain.com
optionally followed by all of a literal /
, optionally followed by a literal home
, optionally followed by a literal ?
and any number of other characters.
You can test it here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With