最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to Match Specific URL with Query String - Stack Overflow

programmeradmin4浏览0评论

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. - Pass
  • http://some.test.domain./ - Pass
  • http://some.test.domain./home - Pass
  • http://some.test.domain./?id=999 - Pass
  • http://some.test.domain./home?id=888&rt=000 - Pass
  • http://some.test.domain./other - Fail
  • http://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
Add a ment  | 

2 Answers 2

Reset to default 9

A 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"
发布评论

评论列表(0)

  1. 暂无评论