Javascript 如何向已经包含其他参数和锚点的 URL 添加参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6953944/
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
How to add parameters to a URL that already contains other parameters and maybe an anchor
提问by skerit
I'm wondering how I can add a new parameter to an existing url. The problem is: the url may also contain an anchor.
我想知道如何向现有 url 添加新参数。问题是:url 也可能包含一个锚点。
For example:
例如:
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
回答by skerit
I used parts of The Awesome One's solution, and a solution found on this question:
我使用了The Awesome One的部分解决方案,以及在这个问题上找到的解决方案:
Adding a parameter to the URL with JavaScript
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;
};
Example: addParameter('http://www.example.com?foo=bar#hashme', 'bla', 'valuebla', false)
例子: addParameter('http://www.example.com?foo=bar#hashme', 'bla', 'valuebla', false)
Results in http://www.example.com?foo=bar&bla=valuebla#hashme
结果是 http://www.example.com?foo=bar&bla=valuebla#hashme
回答by freedev
This can be another good solution, this version is even able to replace the parameter if it already exists, add parameter without value:
这可能是另一个很好的解决方案,这个版本甚至可以替换已经存在的参数,添加没有值的参数:
function addParam(url, param, value) {
var a = document.createElement('a'), regex = /(?:\?|&|&)+([^=]+)(?:=([^&]*))*/g;
var match, str = []; a.href = url; param = encodeURIComponent(param);
while (match = regex.exec(a.search))
if (param != match[1]) str.push(match[1]+(match[2]?"="+match[2]:""));
str.push(param+(value?"="+ encodeURIComponent(value):""));
a.search = str.join("&");
return a.href;
}
url = "http://www.example.com#hashme";
newurl = addParam(url, "ciao", "1");
alert(newurl);
回答by Srinivas Gowda
You can use this JS lib called URI.JS
你可以使用这个名为URI.JS 的JS 库
// mutating URLs
URI("http://example.org/foo.html?hello=world")
.username("rodneyrehm")
// -> http://[email protected]/foo.html?hello=world
.username("")
// -> http://example.org/foo.html?hello=world
.directory("bar")
// -> http://example.org/bar/foo.html?hello=world
.suffix("xml")
// -> http://example.org/bar/foo.xml?hello=world
.hash("hackernews")
// -> http://example.org/bar/foo.xml?hello=world#hackernews
.fragment("")
// -> http://example.org/bar/foo.xml?hello=world
.search("") // alias of .query()
// -> http://example.org/bar/foo.xml
.tld("com")
// -> http://example.com/bar/foo.xml
.search({ foo: "bar", hello: ["world", "mars"] });
// -> http://example.com/bar/foo.xml?foo=bar&hello=world&hello=mars
or
或者
URI("?hello=world")
.addSearch("hello", "mars")
// -> ?hello=world&hello=mars
.addSearch({ foo: ["bar", "baz"] })
// -> ?hello=world&hello=mars&foo=bar&foo=baz
.removeSearch("hello", "mars")
// -> ?hello=world&foo=bar&foo=baz
.removeSearch("foo")
// -> ?hello=world
回答by Sanghyun Lee
Try this:
尝试这个:
location.href = location.href.replace(location.hash, '') + '&x=y' + location.hash
Update
更新
What about this:
那这个呢:
var a = document.createElement('a');
a.href = "http://www.example.com?foo=bar#hashme";
var url = a.href.replace(a.hash, '') + '&x=y' + a.hash;
I found out that the location object can be created by an anchor element(from Creating a new Location object in javascript).
我发现位置对象可以由锚元素创建(来自在 javascript 中创建新的位置对象)。
回答by Some Guy
Easy.
简单。
<script>
function addPar(URL,param,value){
var url = URL;
var hash = url.indexOf('#');
if(hash==-1)hash=url.length;
var partOne = url.substring(0,hash);
var partTwo = url.substring(hash,url.length);
var newURL = partOne+'&'+param+'='+value+partTwo
return newURL;
}
document.write(addPar('http://www.example.com?foo=bar','x','y')) // returns what you asked for
</script>
The code could be modified a bit, and made a little more efficient, but this should work fine.
代码可以稍微修改一下,提高一点效率,但这应该可以正常工作。
@Sangol's solution's better. Didn't know a location.hash property existed.
@Sangol 的解决方案更好。不知道 location.hash 属性存在。
回答by rkb
Here is an improved version of the answer by @skerit. This one supports #
in URL path.
这是@skerit 答案的改进版本。这个支持#
在 URL 路径中。
function addParameter(url, parameterName, parameterValue, atStart/*Add param before others*/) {
var replaceDuplicates = true;
var cl, urlhash;
parameterName = encodeURIComponent(parameterName);
parameterValue = encodeURIComponent(parameterValue);
if (url.lastIndexOf('#') > 0) {
cl = url.lastIndexOf('#');
urlhash = url.substring(cl, url.length);
} else {
urlhash = '';
cl = url.length;
}
var 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;
}
Examples:
例子:
addParameter('http://www.example.com?foo=bar#hashme', 'bla', 'valuebla', false);
// Returns: http://www.example.com?foo=bar&bla=valuebla#hashme
addParameter('http://www.example.com/#iAmNotUrlHash/?foo=bar#hashme', 'bla', 'valuebla', false);
// Returns: http://www.example.com/#iAmNotUrlHash/?foo=bar&bla=valuebla#hashme
回答by slaphappy
Something like this ?
像这样的东西?
var param = "x=y";
var split = url.split('#');
url = split[0] + '&' + param + "#" + split[1];
回答by Maciej Krawczyk
@freedev answer is great, but if you need something very simple (to insert key=value pair to the url and assume that key doesn't already exist), there's a much faster way to do it:
@freedev 的回答很好,但是如果您需要一些非常简单的东西(将 key=value 对插入到 url 并假设 key 不存在),那么有一种更快的方法:
var addSearchParam = function(url,keyEqualsValue) {
var parts=url.split('#');
parts[0]=parts[0]+(( parts[0].indexOf('?') !== -1) ? '&' : '?')+keyEqualsValue;
return parts.join('#');
}
Example usage: addSearchParam('http://localhost?a=1#hash','b=5');
用法示例: addSearchParam(' http://localhost?a=1#hash','b=5');
回答by Dhaval dave
I always use this code, and its working fine ...
我总是使用这个代码,它工作正常......
var currenturl=location.href;
var url = location.href+"?ts="+true;
window.location.replace(url,"_self");