Hi I'm trying to match a specific URL that allows for query strings. Basically I need the following to happen:
- Pass
/
- Pass- Pass
/?id=999
- Pass;rt=000
- Pass- Fail
- Fail
Here is what I have so far:
var pattern = new RegExp('^(https?:\/\/some\.test\.domain\(\/{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.
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.
- Passhttp://some.test.domain./
- Passhttp://some.test.domain./home
- Passhttp://some.test.domain./?id=999
- Passhttp://some.test.domain./home?id=888&rt=000
- Passhttp://some.test.domain./other
- Failhttp://some.test.domain./another?id=999
- Fail
Here is what I have so far:
var pattern = new RegExp('^(https?:\/\/some\.test\.domain\.(\/{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.
Share Improve this question asked Aug 29, 2013 at 20:52 Sam G. DanielSam G. Daniel 1031 gold badge1 silver badge5 bronze badges 3-
1
Can you explain why those that pass pass and why those that fail fail? What is the logic here? Are only nothing and
/home
allowed? – James Montagne Commented Aug 29, 2013 at 20:53 - @JamesMontagne I only want the first five conditions to work. Anything else should fail. – Sam G. Daniel Commented Aug 29, 2013 at 20:58
- @progenhard Yes, I also need to get the top five links to pass. – Sam G. Daniel Commented Aug 29, 2013 at 21:03
2 Answers
Reset to default 9A pattern like this should work (at least for your specific domain)
/^http:\/\/some\.test\.domain\.(\/(home)?(\?.*)?)?$/
This will match a literal http://some.test.domain.
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./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./?qs=1").attr('path')
"/"
purl("http://some.test.domain./other").attr("path")
"/other"
purl("http://some.test.domain./home").attr("path")
"/home"