使用正则表达式,我想编写一个带有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
提前致谢, 罗斯
答案 0 :(得分:3)
不,你不能用一个正则表达式来做,但功能非常简单,我已经用你的所有例子进行了测试,所以它应该工作:
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;
}
答案 1 :(得分:0)
试试这个,
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);
}