我想使用正则表达式编写一个函数,该函数将接受一个 URL 和一个参数名称:ReplaceParamValueinURL (url, param, value)
。
如果参数存在,它将替换URL中的值。
如果该参数不存在,它会将其与值一起添加到 URL。
如果参数存在但没有值,它将把值添加到参数中。
在正则表达式查找和替换中是否有一种优雅的方式来完成所有这三个操作?
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?
我想这是一个很常见的情况,但可能有很多极端情况。
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3#test, a , 2)
returns http://google.com?a=2&b&c=3#test
最佳答案
不,你不能用一个正则表达式来做,但这个函数非常简单,我已经用你所有的例子测试过它,所以它应该可以工作:
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 正则表达式替换 URL 中的获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17061502/