Remove querystring from URL

JavascriptJquery

Javascript Problem Overview


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'

Javascript Solutions


Solution 1 - Javascript

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];
}

Solution 2 - Javascript

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"

Solution 3 - Javascript

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

Solution 4 - Javascript

var path = "path/to/myfile.png?foo=bar#hash";

console.log(
    path.replace(/(\?.*)|(#.*)/g, "")
);

Solution 5 - Javascript

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

Solution 6 - Javascript

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();

Solution 7 - Javascript

A simple way is you can do as follows

public static String stripQueryStringAndHashFromPath(String uri) {
 return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}

Solution 8 - Javascript

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

Solution 9 - Javascript

If you're into RegEx....

var newURL = testURL.match(new RegExp("[^?]+"))

Solution 10 - Javascript

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', '');

Solution 11 - Javascript

If you need to perform complex operation on URL, you can take a look to the jQuery url parser plugin.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMathias FView Question on Stackoverflow
Solution 1 - JavascriptRobustoView Answer on Stackoverflow
Solution 2 - JavascriptDaniel VassalloView Answer on Stackoverflow
Solution 3 - Javascriptdamitj07View Answer on Stackoverflow
Solution 4 - JavascriptyckartView Answer on Stackoverflow
Solution 5 - Javascriptuser1050755View Answer on Stackoverflow
Solution 6 - JavascriptCode CookerView Answer on Stackoverflow
Solution 7 - Javascriptkarthik mView Answer on Stackoverflow
Solution 8 - JavascriptgolopotView Answer on Stackoverflow
Solution 9 - JavascriptplodderView Answer on Stackoverflow
Solution 10 - JavascriptvikydView Answer on Stackoverflow
Solution 11 - JavascriptBoris GuéryView Answer on Stackoverflow