如何将参数添加到已包含其他参数且可能是锚点的URL [英] How to add parameters to a URL that already contains other parameters and maybe an anchor
本文介绍了如何将参数添加到已包含其他参数且可能是锚点的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何向现有网址添加新参数。
问题是:url也可能包含一个锚点。
I'm wondering how I can add a new parameter to an existing url. The problem is: the url may also contain an anchor.
例如:
http://www.example.com?foo=bar#hashme
我想为它添加另一个参数,因此它会导致这个:
And I want to add another parameter to it, so it results in this:
http://www.example.com?foo=bar&x=y#hashme
推荐答案
我使用了 The Awesome One 的部分内容解决方案,以及在这个问题上找到的解决方案:
I used parts of The Awesome One's solution, and a solution found on this question:
将它们组合到此脚本中:
Combining them into this script:
function addParameter(url, parameterName, parameterValue, atStart/*Add param before others*/){
replaceDuplicates = true;
if(url.indexOf('#') > 0){
var cl = url.indexOf('#');
urlhash = url.substring(url.indexOf('#'),url.length);
} else {
urlhash = '';
cl = url.length;
}
sourceUrl = url.substring(0,cl);
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1)
{
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++)
{
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] == parameterName))
{
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterParts[0] + "=" + (parameterParts[1]?parameterParts[1]:'');
}
}
}
if (newQueryString == "")
newQueryString = "?";
if(atStart){
newQueryString = '?'+ parameterName + "=" + parameterValue + (newQueryString.length>1?'&'+newQueryString.substring(1):'');
} else {
if (newQueryString !== "" && newQueryString != '?')
newQueryString += "&";
newQueryString += parameterName + "=" + (parameterValue?parameterValue:'');
}
return urlParts[0] + newQueryString + urlhash;
};
示例: addParameter('http://www.example.com? foo = bar #hashme','bla','valuebla',false)
结果 http:/ /www.example.com?foo=bar&bla=valuebla#hashme
这篇关于如何将参数添加到已包含其他参数且可能是锚点的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文