2013-06-12 20 views
1

使用正則表達式,我想編寫一個函數,它將採用URL和參數名稱:ReplaceParamValueinURL (url, param, value)Javascript Reg表達式替換URL中的Get參數

如果參數存在,它將替換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 

由於提前, 羅斯

回答

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

您好,我才意識到這個解決方案不符合我的真實URL的http工作://本地主機: 8080/signup.htmlfirst_name = Ross&username = Ross.ya%2B1%40gmail.com&business_id = 2&pin = 190854&pId = 258243806&last_name = Ya&debug = true#/ signupnew –

+0

爲什麼?怎麼了? – mck89

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