Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to Match Specific URL with Query String

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.

like image 392
Sam G. Daniel Avatar asked Aug 29 '13 20:08

Sam G. Daniel


People also ask

How can I tell if a URL has a query string?

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.

Does URL path include query?

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).

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


1 Answers

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

like image 81
p.s.w.g Avatar answered Oct 10 '22 01:10

p.s.w.g