0

I'm checking for a very specific pattern in URLs so that a set of code is only executed on the correct type of page. Currently, I've got something like:

/^http:\/\/www\.example\.com\/(?:example\/[^\/]+\/?)?$/;

So, it'll return true for example.com and example.com/example/anythinghere/. However, sometimes this website will append arguments such as ?postCount=25 or something to the end of the URL, so you get:

example.com/example/anythinghere/?postCount=25

Because of this, if I throw the current expression into a conditional, it will return false should there be URL arguments. How would I best go about changing the regex expression to allow for an optional URL argument wildcard, so that, if there's a question mark followed by any additional information, it will always return true, and, if it's omitted, it will still return true?

It would need to return true for:

http://www.example.com/?argumentshere

and

http://www.example.com/example/anythinghere/?argumentshere

As well as those same URLs without the extra arguments.

Jtaylorapps
  • 5,680
  • 8
  • 40
  • 56

3 Answers3

1

Try following regex:

^http:\/\/www\.example\.com(?:\/example\/[^\/]+\/?)?\??.*$

regex101 demo

jkshah
  • 11,387
  • 6
  • 35
  • 45
0

You can build the URL without parameters and compare that with your current expression.

location.protocol + '//' + location.host + location.pathname

How to get the URL without any parameters in JavaScript?

Community
  • 1
  • 1
Derek
  • 3,438
  • 1
  • 17
  • 35
0

Upgrading my comment to an answer:

 /^http:\/\/www\.example\.com\/(?:example\/[^\/]+\/?)?$/;

Meanse:

 /^    # start of string
      http:\/\/www\.example\.com\/  #literal http://www.example.com/
      (?:           
         example\/[^\/]+\/? #followed by example/whatever (optionally closed by /)
      )?
      $ end-of-string
  /

The main problem here, is your requirements ("followed by an optional querystring") does not match you regex (which requires an end-of-string). We solve it by:

 /^    # start of string
      http:\/\/www\.example\.com\/  #literal http://www.example.com/
      (?:           
         example\/[^\/]+\/? #followed by example/whatever (optionally closed by /)
      )?
      (\?|$) followed by either an end-of-string (original), or a literal `?` (which in url context means the rest is a query string and not a path anymore).
  /
Wrikken
  • 69,272
  • 8
  • 97
  • 136