Javascript Reg Expression替换URL中的Get Parameter

使用正则表达式,我想编写一个将采用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很简单,我已经测试了所有你的例子,所以它应该工作:

 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; } 

试试这个,

 function ReplaceParamValueinURL(url , replceparam , replaceValue) { regExpression = "(\\?|&)"+replceparam+"(=).(&|)"; var regExpS = new RegExp(regExpression, "gm"); var getmatch = url.match(regExpS); var regExpSEq = new RegExp("=", "g"); var getEqalpostion = regExpSEq.exec(getmatch); var newValue; if(getmatch[0].charAt(getmatch[0].length - 1) != "&") { var subSrtingToReplace = getmatch[0].substring((getEqalpostion.index+ 1),getmatch[0].length ); newValue = getmatch[0].replace(subSrtingToReplace , replaceValue); } else { var subSrtingToReplace = getmatch[0].substring((getEqalpostion.index+ 1) , getmatch[0].length - 1 ); newValue = getmatch[0].replace(subSrtingToReplace , replaceValue); } return returnString = url.replace(regExpS , newValue); }