213

What is an easy way to remove the querystring from a Path in Javascript? I have seen a plugin for Jquery that uses window.location.search. I can not do that: The URL in my case is a variable that is set from AJAX.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'

Edit after 13 years

At some point in the last decade Javascript got some Url handling.

asked Mar 29, 2010 at 20:18
0

12 Answers 12

441

An easy way to get this is:

function getPathFromUrl(url) {
 return url.split("?")[0];
}

For those who also wish to remove the hash (not part of the original question) when no querystring exists, that requires a little bit more:

function stripQueryStringAndHashFromPath(url) {
 return url.split("?")[0].split("#")[0];
}

EDIT

@caub (originally @crl) suggested a simpler combo that works for both query string and hash (though it uses RegExp, in case anyone has a problem with that):

function getPathFromUrl(url) {
 return url.split(/[?#]/)[0];
}
answered Mar 29, 2010 at 20:35
Sign up to request clarification or add additional context in comments.

9 Comments

+1... Actually split() is better than substring() in this case.
Marginal optimisation if it matters (probably not): split('?', 1)[0].
@ChristianVielma: This ? is a string literal, not a regular expression.
@Robusto I'm sorry, my bad... I was checking it in Java (which interprets it as a regex) :(
Hey Robusto, and why not .split(/[?#]/)[0]?
|
36

2nd Update: In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
var i;
// Testing the substring method
i = 0;
console.time('10k substring');
while (i < 10000) {
 testURL.substring(0, testURL.indexOf('?'));
 i++;
}
console.timeEnd('10k substring');
// Testing the split method
i = 0;
console.time('10k split');
while (i < 10000) {
 testURL.split('?')[0]; 
 i++;
}
console.timeEnd('10k split');
// Testing the RegEx method
i = 0;
var re = new RegExp("[^?]+");
console.time('10k regex');
while (i < 10000) {
 testURL.match(re)[0]; 
 i++;
}
console.timeEnd('10k regex');

Results in Firefox 3.5.8 on Mac OS X 10.6.2:

10k substring: 16ms
10k split: 25ms
10k regex: 44ms

Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:

10k substring: 14ms
10k split: 20ms
10k regex: 15ms

Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.


1st UPDATE: Actually the split() method suggested by Robusto is a better solution that the one I suggested earlier, since it will work even when there is no querystring:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.split('?')[0]; // Returns: "/Products/List"
var testURL2 = '/Products/List';
testURL2.split('?')[0]; // Returns: "/Products/List"

Original Answer:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"
answered Mar 29, 2010 at 20:21

4 Comments

O_O Very comprehensive indeed, but... why? The most flexible and appropriate method obviously wins, speed is of absolutely no concern here.
@deceze: Just for curiosity... And because there was an argument about the performance of the regex method in the comments of the Angus' answer.
Very interesting, Daniel. And if I ever have to do 10K URL parses on a page I'm going to seek another line of work. :)
I'm actually a bit blown away that one can do 10k regex matches in 44ms. In the future, I think I will be inclined to use them more.
34

This may be an old question but I have tried this method to remove query params. Seems to work smoothly for me as I needed a reload as well combined with removing of query params.

window.location.href = window.location.origin + window.location.pathname;

Also since I am using simple string addition operation I am guessing the performance will be good. But Still worth comparing with snippets in this answer

answered Jan 31, 2018 at 12:19

2 Comments

Best solution IMO. Are there are downsides or cases where this won't work?
The reason is that the OP specifically states that they can't use window.location and have to operate on a bare string exclusively.
32

var u = new URL('https://server.de/test?q#h')
u.hash = ''
u.search = ''
console.log(u.toString())

answered Apr 28, 2021 at 16:53

2 Comments

This is the only valid answer in this thread.
This is better and even works in nodejs, but the performance is just a little worse if you have to process many thousands of URLs per second.
6

I can understand how painful things were before, In modern days you can get this super easily like below

let url = new URL('https://example.com?foo=1&bar=2&foo=3');
let params = new URLSearchParams(url.search);
// Delete the foo parameter.
params.delete('foo'); //Query string is now: 'bar=2'
// now join the query param and host
let newUrl = url.origin + '/' + params.toString();
answered Apr 30, 2021 at 6:26

2 Comments

let params = url.searchParams suffices.
This does not take instances into consideration where you have a path
4
var path = "path/to/myfile.png?foo=bar#hash";
console.log(
 path.replace(/(\?.*)|(#.*)/g, "")
);
answered May 26, 2013 at 15:29

Comments

2

A simple way is you can do as follows

public static String stripQueryStringAndHashFromPath(String uri) {
 return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}
answered Dec 21, 2012 at 23:00

Comments

2

An approach using the standard URL:

/**
 * @param {string} path - A path starting with "/"
 * @return {string}
 */
function getPathname(path) {
 return new URL(`http://_${path}`).pathname
}
getPathname('/foo/bar?cat=5') // /foo/bar
answered Jun 13, 2019 at 8:10

2 Comments

@Brad what does the protocol matter when all he does is returning the pathname afterwards?
@The Fool - the new URL() will fail with 'Invalid URL` error message otherwise
1

If you're into RegEx....

var newURL = testURL.match(new RegExp("[^?]+"))
answered Mar 29, 2010 at 20:45

6 Comments

the regexp is slow one - go with the easy fast way.
@Angus: Your loop is giving you "A script may be busy..." because you forgot to increment a++;. Fixing the tests, in my Firefox 3.6 on an iMac 2.93Ghz Core 2 Duo, I get 8ms for the RegEx, and 3ms for the split method... Nevertheless +1 for the answer, because it is still another option.
thanks - I fixed it a few mins ago! - but the point is when you are talking 0.000005 seconds even for the reg exp operation, performance is not an issue for any solution :-)
match() returns an object. You probably don't want that. Call toString() on it (or +'').
Bob - good catch. Actually it returns an array of matches - an Array of strings in this case. So testURL.match(new RegExp("[^?]+"))[0] does it
|
1

If using backbone.js (which contains url anchor as route), url query string may appear:

  1. before url anchor:

    var url = 'http://example.com?a=1&b=3#routepath/subpath';
    
  2. after url anchor:

    var url = 'http://example.com#routepath/subpath?a=1&b=3';
    

Solution:

window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
answered Nov 8, 2016 at 2:46

Comments

0

You can use URL with a dummy base (e.g. http://localhost ) as second parameter:

new URL('/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc',
 'http://localhost')
.pathname
//Outputs: /Products/List

It works also for full urls:

new URL('http://someSite.com/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc',
 'http://localhost')
.pathname
//Outputs: /Products/List
answered May 9 at 11:06

Comments

-1

Using URL

Removing specific param:

const url = new URL('https://example.com?foo=1&bar=2');
url.searchParams.delete("foo");
console.log(url.href);

Removing all params:

const url = new URL('https://example.com?foo=1&bar=2');
url.search = "";
console.log(url.href);
answered Mar 25, 2023 at 8:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.