11

I would like to match a path in a Url, but ignoring the querystring. The regex should include an optional trailing slash before the querystring.

Example urls that should give a valid match:

/path/?a=123&b=123

/path?a=123&b=123

So the string '/path' should match either of the above urls.

I have tried the following regex: (/path[^?]+).*

But this will only match urls like the first example above: /path/?a=123&b=123

Any idea how i would go about getting it to match the second example without the trailing slash as well?

Regex is a requirement.

1
  • (/path[?]+|/path/[?]+).* Commented Oct 27, 2013 at 21:40

2 Answers 2

9

No need for regexp:

url.split("?")[0];

If you really need it, then try this:

\/path\?*.*

EDIT Actually the most precise regexp should be:

^(\/path)(\/?\?{0}|\/?\?{1}.*)$

because you want to match either /path or /path/ or /path?something or /path/?something and nothing else. Note that ? means "at most one" while \? means a question mark.

BTW: What kind of routing library does not handle query strings?? I suggest using something else.

Sign up to request clarification or add additional context in comments.

3 Comments

I should have noted that i am required to use regex. I am using a routing library that uses regex to match urls.
@JCoder23 Updated one more time
Im using CasperJS with the PhantomJS webserver module. The web server module is a basic http server (Mongoose), which does not have routing built in. I found a routing library someone wrote for it, that does not support query strings, as in urls will not match if a querystring is appended to the url. So i needed this regex to match a route without the query string, i then patched the routing library to correctly parse out the query string and add it to the request object of the route.
4

http://jsfiddle.net/bJcX3/

var re = /(\/?[^?]*?)\?.*/;

var p1 = "/path/to/something/?a=123&b=123";
var p2 = "/path/to/something/else?a=123&b=123";

var p1_matches = p1.match(re);
var p2_matches = p2.match(re);

document.write(p1_matches[1] + "<br>");
document.write(p2_matches[1] + "<br>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.