The JavaScript snippet below will strip a URL of a given variable. The function requires, two parameter, the URL you would like to manipulate and the name of the variable that you would like to remove.
1 2 3 4 5 6 7 8 9 10 | function removeVariableFromURL(url_string, variable_name) { var URL = String(url_string); var regex = new RegExp( "\\?" + variable_name + "=[^&]*&?", "gi"); URL = URL.replace(regex,'?'); regex = new RegExp( "\\&" + variable_name + "=[^&]*&?", "gi"); URL = URL.replace(regex,'&'); URL = URL.replace(/(\?|&)$/,''); regex = null; return URL; } |
With the function included in a script file or written in the head of the HTML. You should call and use the function like this.
1 2 | var stripped_url = removeVariableFromURL(top.location.href, q); top.location.href = stripped_url; |
The example above will setup a variable called stripped_url to store the altered URL. It is assigned the returned value of removeVariableFromURL(). The parameters that are passed to the function are top.location.href and q. top.location.href is the URL string found in your browser address bar. Q will be the variable that is removed from the URL string. Q can be replaced with anything that you wish. Q would normal be the path variable when using WordPress or Drupal. Finally, the stripped_url will be applied to the top.location.href replacing the existing URL.

Very useful. Thanks.
You’ve created a global variable out of URL in this function — you should add ‘var ‘ in front of the line:
URL = String(url_string);
Should be:
var URL = String(url_string);
Thank you Joe, will make the amend.
Thanks for sharing, it just works and made me very happy!
No problem, glad to hear this was a help to you.
sir, this a a great help can you please set a demo (example) how should i apply on site. i’m new (thanks in advance )