Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to remove query string from a link?

How can I remove a query string from the url of a link? For example I have

<a href="http://example.com/somepath/anotherpath?title=dog">The Link</a>

How can I remove just the ?title=dog from the url using javascript/jquery?

like image 680
Dustin Avatar asked Jul 18 '12 14:07

Dustin


People also ask

How can remove last parameter from URL in jquery?

replaceState({}, document. title, clean_uri); It remove the query string from URL without reloading page. It is helpful when your URL is long and your server gives the error 414 Request-URI Too Long HTTP status code then using this script you are able to remove all query string and make a short and fresh URL.

How to remove parameter from URL in Javascript?

Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you. To use it, simply do something like this: var originalURL = "http://yourewebsite.com?id=10&color_id=1"; var alteredURL = removeParam("color_id", originalURL);


1 Answers

You can remove the query string from a link by simply changing the search property of the Location object.

$("#your_link")[0].search = "";

Demo: http://jsfiddle.net/uSrmg/1/

Or if you need to target multiple elements:

$("a.someclass").each(function() {
 this.search = "";   
});

Demo: http://jsfiddle.net/uSrmg/4/


If you wish to parse an arbitrary URL to remove the query string, you can inverse the trick explained in this post. For example:

function remove_qs(url) {
    var a = document.createElement('a'); // dummy element
    a.href = url;   // set full url
    a.search = "";  // blank out query string
    return a.href;
}

This should be quite robust as it uses the Location object to do all the parsing.

Example usage: http://jsfiddle.net/uSrmg/


like image 112
Shawn Chin Avatar answered Oct 29 '22 17:10

Shawn Chin