how to remove a querystring on buttonclick?

13,925

Solution 1

What is url? You have to get the url from the window.location object:

$("#querystring").click(function(){
    window.location.href = window.location.href.split('?')[0];
});

Solution 2

To get the url without querystring use this

function getPathFromUrl() {
  var url = window.location.href; 

  if(url.indexOf("?") != -1)
     url = url.split("?")[0];

  return url;
}

Usage

$("#querystring").click(function(){
     alert(getPathFromUrl());//this will alert the url without querystring
});
Share:
13,925
sinini
Author by

sinini

Updated on June 05, 2022

Comments

  • sinini
    sinini almost 2 years

    how can i remove a querystring of an url when clicking a button? my url looks like this:

    www.mysite.com/?tx_felogin_pi1[forgot]=1

    this page shows a form for getting the new password, everything is inside an overlaybox. when the user suddenly remembers his userdata again, i need to provide a link in the box to go back to the signin form (also inside an overlaybox), but i can not use a fix url, because the link (and the overlaybox) should be accessable on every page. so i need a link which removes the querystring, independet of the url before.

    i tried this, but it won't work:

        function getPathFromUrl(url) {
          return url.split("?")[0];
        }
        // from http://stackoverflow.com/questions/2540969/remove-querystring-from-url
    
        $("#querystring").click(getPathFromUrl);
    

    the error in my console is: url.split is not a function...

  • Joseph Silber
    Joseph Silber over 12 years
    No need to ascertain that the string contains a ?. 'test'.split('?')[0] will return test.
  • ShankarSangoli
    ShankarSangoli over 12 years
    Thats correct, but why to split of it does not contain '?'?
  • Joseph Silber
    Joseph Silber over 12 years
    Because, although I did not test it, I doubt that split is more expensive than indexOf (besides for the fact that you'll most likely run them both). Why convolute your code like that?
  • Er.KT
    Er.KT almost 10 years
    superb +1 for your answer
  • Shoaib Iqbal
    Shoaib Iqbal over 7 years
    it reloads the page.