Javascript Reg Expression替换URL中的Get Parameter [英] Javascript Reg Expression to replace Get Parameter in the URL
问题描述
使用正则表达式,我想编写一个带有URL和参数名称的函数: ReplaceParamValueinURL(url,param,value)
。
Using a regular expression, I want to write a function that will take a URL and a parameter name: ReplaceParamValueinURL (url, param, value)
.
如果参数存在,它将替换URL中的值。
如果参数不存在,它会将其与值一起添加到URL。
如果参数存在且没有值,则会将值添加到参数中。
If the parameter exists, it will replace the value in the URL. If the parameter doesn't exist, it will add it to the URL along with the value. If the parameter exists with no value, it will add the value to the parameter.
在正则表达式查找和替换中是否有一种优雅的方式来完成所有三个?
Is there an elegant way of doing all three in regex find and replace?
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, a , 4)
returns http://google.com?a=4&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, a , 4)
returns http://google.com?a=4&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, c , 4)
returns http://google.com?a=1&b=2&c=4
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, d , 5)
returns http://google.com?a=1&b=2&c=3&d=5
ReplaceParamValueinURL ("http://google.com?aaa=0&a=1&b=2&c=3, a , 6)
returns http://google.com?aaa=0&a=6&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3, b , 2)
returns http://google.com?a=1&b=2&c=3
I am hoping to do this with Reg ex instead of split. I really appreciate it if you can explain your answer if the regex is too complex. Is there a Jquery function that already does this?
我想这是一个非常常见的情况,但可能有很多极端情况。
I guess it's a very common case but can have many corner cases.
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3#test, a , 2)
returns http://google.com?a=2&b&c=3#test
提前致谢,
Ross
Thanks in advance, Ross
推荐答案
不能用一个正则表达式来做,但功能非常简单,我已经用你的所有例子对它进行了测试,所以它应该可以工作:
No you can't do it with a single regexp, but the function is pretty simple, i've tested it with all your examples so it should work:
function ReplaceParamValueinURL (url, name, val) {
//Try to replace the parameter if it's present in the url
var count = 0;
url = url.replace(new RegExp("([\\?&]" + name + "=)[^&]+"), function (a, match) {
count = 1;
return match + val;
});
//If The parameter is not present in the url append it
if (!count) {
url += (url.indexOf("?") >=0 ? "&" : "?") + name + "=" + val;
}
return url;
}
这篇关于Javascript Reg Expression替换URL中的Get Parameter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!