URL match path without query string

I would like to map the path in Url, but ignoring the request. The regular expression must include an optional trailing slash before the call.

Examples of URLs that must match the action:

/path/?a=123&b=123 /path?a=123&b=123 

So, the line '/ path' must match any of the above URLs.

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

But this will only match the URLs, such as the first example above: /path/?a=123&b=123

Any idea how I could make it fit the second example without a trailing slash?

Regex is a requirement.

+6
source share
2 answers

No regexp needed:

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

If you really need it, try the following:

 \/path\?*.* 

EDIT In fact, the most accurate regular expression should be:

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

because you want to match either /path , or /path/ or /path?something or /path/?something , and nothing more. Please note that ? means "no more than one", but \? means a question mark.

BTW: Which routing library does not process query strings? I suggest using something else.

+3
source

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>"); 
+3
source

Source: https://habr.com/ru/post/956834/


All Articles