javascript jQuery:如何从链接中删除查询字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11543398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: How to remove query string from a link?
提问by Dustin
How can I remove a query string from the url of a link? For example I have
如何从链接的 url 中删除查询字符串?例如我有
<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?
如何?title=dog
使用 javascript/jquery 从 url 中删除?
回答by Shawn Chin
You can remove the query string from a link by simply changing the search
propertyof the Locationobject.
您可以通过简单地更改Location对象的search
属性来从链接中删除查询字符串。
$("#your_link")[0].search = "";
Demo: http://jsfiddle.net/uSrmg/1/
演示: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/
演示: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:
如果你想解析任意URL删除的查询字符串,可以逆的伎俩在解释这个职位。例如:
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 Locationobject to do all the parsing.
这应该非常健壮,因为它使用Location对象进行所有解析。
Example usage: http://jsfiddle.net/uSrmg/
用法示例:http: //jsfiddle.net/uSrmg/
回答by Alok Jha
There is one more way to replace search with blank.
还有一种用空白替换搜索的方法。
String(document.location.href).replace("&title=dog", "");
回答by jbabey
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]);
}
回答by Willem
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:
在“?”上拆分 并获得第一项。如果要更改页面上所有链接的 url,则可以使用以下代码:
$('a').each(function(i,el){
$(el).attr('href', $(el).attr('href').split('?')[0]);
});
回答by Ghanshyam Singh
You can split the query string from the url on page load as:-
您可以在页面加载时将查询字符串从 url 拆分为:-
$(function(){
if(Modernizr.history)
{
history.replaceState({},"",location.href.split("?")[0]);
}
});
回答by Gnana Sekar
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
通过javascript在url中拆分特定的字符串查询参数