Dustin Dustin - 3 months ago 20
Javascript Question

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
from the url using javascript/jquery?


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/