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
- Pass http://some.test.domain.com/
- Pass http://some.test.domain.com/home
- Pass http://some.test.domain.com/?id=999
- Pass http://some.test.domain.com/home?id=888&rt=000
- Pass http://some.test.domain.com/other
- Fail http://some.test.domain.com/another?id=999
- Fail Here 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.
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
Don't use a Regex, use an URL parser. You could use purl
Then, you'll do:
url = "http://some.test.domain.com/home" // Or any other
purl(url).attr('path') // is equal to "home" here.
You'll just need to check .attr('path')
against your accepted paths (seemingly ""
, "/"
, and "home"
).
Here's some sample output:
purl("http://some.test.domain.com/?qs=1").attr('path')
"/"
purl("http://some.test.domain.com/other").attr("path")
"/other"
purl("http://some.test.domain.com/home").attr("path")
"/home"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.