Javascript 在javascript中搜索和替换特定的查询字符串参数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5413899/
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
Search and replace specific query string parameter value in javascript
提问by TopCoder
I have a string which is something like this :
我有一个像这样的字符串:
a_href= "www.google.com/test_ref=abc";
I need to search for test_ref=abc in thisabove strinng and replace it with new value
我需要在上面的字符串中搜索 test_ref=abc 并将其替换为新值
var updated_test_ref = "xyz";
a_href ="www.google.com/test_ref=updated_test_ref"
i.e
IE
www.google.com/test_ref=xyz.
How can we do this ?
我们应该怎么做 ?
EDIT:
编辑:
test_ref value can be a URL link in itself something like http://google.com?param1=test1¶m2=test2. I need to capture complete value not till first &.
test_ref 值本身可以是一个 URL 链接,例如http://google.com?param1=test1¶m2=test2。我需要在第一个 & 之前捕获完整的价值。
回答by Mark Kahn
a_href = a_href.replace(/(test_ref=)[^\&]+/, '' + updated_test_ref);
回答by Nejc Lepen
Based on this discussion I have fixed the Chris function (problem with regex string!)
基于此讨论,我修复了 Chris 函数(正则表达式字符串的问题!)
function updateUrlParameter(url, param, value){
var regex = new RegExp('('+param+'=)[^\&]+');
return url.replace( regex , '' + value);
}
回答by Chris
Based on this discussion I have created a references function. enjoy
基于这个讨论,我创建了一个引用函数。请享用
updateUrlParameter(url, param, value){
var regex = new RegExp("/([?|&]" + param + "=)[^\&]+/");
return url.replace(regex, '' + value);
}
回答by souravb
I was searching for this solution for few hours and finally stumbled upon this question. I have tried all the solutions here. But there is still an issue while replacing specific param value in url. Lets take a sample url like
我一直在寻找这个解决方案几个小时,最后偶然发现了这个问题。我已经尝试了这里的所有解决方案。但是在替换 url 中的特定参数值时仍然存在问题。让我们以一个示例网址为例
http://google.com?param1=test1¶m2=test2&anotherparam1=test3
http://google.com?param1=test1¶m2=test2&anotherparam1=test3
and the updated url should be like
更新后的网址应该是这样的
http://google.com?param1=newtest¶m2=test2&anotherparam1=test3
, where value of param1
is changed.
http://google.com?param1=newtest¶m2=test2&anotherparam1=test3
,其中的值param1
发生了变化。
In this case, as @Panthrohas pointed out, adding [?|&]
before the querying string ensures that anotherparam1
is not replaced. But this solution also adds the '?' or '&' character to the matching string. So while replacing the matched characters, the '?' or '&' will also get replaced. You will not know exactly which character is replaced so you cannot append that character as well.
在这种情况下,正如@ Panthro指出的那样,[?|&]
在查询字符串之前添加可确保anotherparam1
不会被替换。但是这个解决方案还添加了“?” 或 '&' 字符到匹配的字符串。因此,在替换匹配的字符时,'?' 或 '&' 也将被替换。您不会确切知道替换了哪个字符,因此您也无法附加该字符。
The solution is to match '?' or '&' as preceding characters only.
解决方案是匹配“?” 或 '&' 仅作为前面的字符。
I have re-written the function of @Chris, fixing the issue with string and have added case insensitive argument.
我已经重新编写的@功能克里斯,固定用绳子的问题,并增加了不区分大小写的说法。
updateUrlParameter(url, param, value){
var regex = new RegExp('(?<=[?|&])(' + param + '=)[^\&]+', 'i');
// return url.replace(regex, param + '=' + value);
return url.replace(regex, param + '=' + value);
}
Here (?<=[?|&])
means, the regex will match '?' or '&' char and will take the string that occurs after the specified character (looks behind the character). That means only param1=test1
substring will be matched and replaced.
这里的(?<=[?|&])
意思是,正则表达式将匹配 '?' 或 '&' char 并将采用出现在指定字符之后的字符串(在字符后面)。这意味着只会param1=test1
匹配和替换子字符串。
回答by Roni Tovi
I know this is a bit dirty code but I've achieved what I was looking for. It replaces the given query string or adds new one if it doesn't exist yet.
我知道这是一个有点脏的代码,但我已经实现了我想要的。它替换给定的查询字符串或添加新的(如果尚不存在)。
function updateUrlParameter(url, param, value) {
var index = url.indexOf("?");
if (index > 0) {
var u = url.substring(index + 1).split("&");
var params = new Array(u.length);
var p;
var found = false;
for (var i = 0; i < u.length; i++) {
params[i] = u[i].split("=");
if (params[i][0] === param) {
params[i][1] = value;
found = true;
}
}
if (!found) {
params.push(new Array(2));
params[params.length - 1][0] = param;
params[params.length - 1][1] = value;
}
var res = url.substring(0, index + 1) + params[0][0] + "=" + params[0][1];
for (var i = 1; i < params.length; i++) {
res += "&" + params[i][0] + "=" + params[i][1];
}
return res;
} else {
return url + "?" + param + "=" + value;
}
}
It will work when given regular URL addresses like:
当给定常规 URL 地址时,它将起作用,例如:
updateUrlParameter('https://www.example.com/some.aspx?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/some.aspx','id','5');
Please noteIt will NOT work only if any of the query string parameter name or value contains "=" and/or "&" chars. It will work just fine behind that.
请注意,仅当任何查询字符串参数名称或值包含“=”和/或“&”字符时,它才会起作用。在这之后它会工作得很好。
回答by Mohamed.Abdo
*Java script code to find a specific query string and replace its value *
*用于查找特定查询字符串并替换其值的 Java 脚本代码 *
('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});