像
?a=1&b=2&c=3
我只想改变b = 6,同时保持其他的相同,怎么做?
答案 0 :(得分:2)
如果您必须用b = newBValue
替换任何b = XXX,请执行以下功能function ReplaceB(strQuery,newBValue)
{
var idxStart= strQuery.indexOf("b=")
if(idxStart<0)
return; // b= not found, nothing to change
var idxFin=strQuery.substr(0,idxStart).indexOf("&");
var newQuery;
if(idxFin<0)
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue
else
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue+strQuery.substr(idxStart+idxFin)
return newQuery;
}
答案 1 :(得分:1)
var test = "?a=1&b=2&c=3".replace(/b=2/gi,"b=6");
alert(test);
var test = "?a=1&b=2&c=3".replace("b=2","b=6");
alert(test);
var test = "?a=1&b=2&c=3".split("b=2").join("b=6");
alert(test);
想要更改为b的值而不管它已经是多少?使用:
var test = "?a=1&b=2&c=3".replace(/b=\d/gi, "b=6");
alert(test);
答案 2 :(得分:1)
var queryStr = "?a=1&b=2&c=3";
var startTag = "b=";
var endTag = "&";
var index1 = queryStr.indexOf(startTag) + startTag.length;
var index2 = queryStr.indexOf(endTag,index1);
var newValue = 23;
queryStr = queryStr.substr(0, index1) + newValue + queryStr.substr(index2);
alert(queryStr);
请在此处查看:http://jsfiddle.net/aQL8p/
答案 3 :(得分:1)
var queryString = '?a=1&b=2&c=3'.replace(/([?&;])b=2([$&;])/g, '$1b=6$2');
(JavaScript正则表达式不支持lookbehinds)。
答案 4 :(得分:1)
这是一个小功能:
jQuery.replaceURLParam = function (oldURL, replaceParam, newVal) {
var iStart = oldURL .indexOf(replaceParam + '=');
var iEnd = oldURL .substring(iStart + 1).indexOf('&');
var sEnd = oldURL .substring(iStart + iEnd + 1);
var sStart = oldURL .substring(0, iStart);
var newURl = sStart + replaceParam + '=' + newVal;
if (iEnd > 0) {
newURl += sEnd;
}
return newURl;
}
document.body.innerHTML = jQuery.replaceURLParam('www.foo.com?a=1&b=2&c=3','b',6);
答案 5 :(得分:0)