Dustin
Dustin

Reputation: 4459

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?

Upvotes: 5

Views: 14610

Answers (6)

Gnana Sekar
Gnana Sekar

Reputation: 29

This code worked for me:

var url = "www.foo.com/test?name=kevin&gender=Male&id=1234";

var res = url.replace("&gender=Male", "");

window.location.href =res;

Split particular string query parameter in url by javascript

Upvotes: 0

Ghanshyam Singh
Ghanshyam Singh

Reputation: 1381

You can split the query string from the url on page load as:-

$(function(){
  if(Modernizr.history)
  {
    history.replaceState({},"",location.href.split("?")[0]);
  }
});

Upvotes: 0

Alok Jha
Alok Jha

Reputation: 572

There is one more way to replace search with blank.

String(document.location.href).replace("&title=dog", "");

Upvotes: 3

Shawn Chin
Shawn Chin

Reputation: 86854

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/


Upvotes: 14

jbabey
jbabey

Reputation: 46647

To remove the querystring from an anchor tag:

var anchor = $('#yourAnchor');
var href = anchor.attr('href');

if (href.indexOf('?') !== -1) {
   anchor.attr('href', href.split('?')[0]);
}

Upvotes: 3

Willem
Willem

Reputation: 5404

var url=$('a').attr('href').split('?')[0];

Split on the "?" and get the first item. If you want to change the url of all links on the page then you can use this code:

$('a').each(function(i,el){ 
    $(el).attr('href', $(el).attr('href').split('?')[0]);
});

Upvotes: 2

Related Questions