JavaScript重定向URL参数的两种方法小结
这篇文章主要介绍的是JavaScript重定向URL参数的两种方法,下面话不多说,直接看示例代码。
一、字符拼接形式
function setUri(para, val) {
var strNewUrl = new String();
var strUrl = new String();
var url = window.location.href;
strUrl = window.location.href;
if (strUrl.indexOf("?") != -1) {
strUrl = strUrl.substr(strUrl.indexOf("?") + 1); //获取参数
if (strUrl.toLowerCase().indexOf(para.toLowerCase()) == -1) { //如果没有找到参数,则直接赋值
strNewUrl = url + "&" + para + "=" + val;
window.location.href = strNewUrl;
} else {
var aParam = strUrl.split("&");
for (var i = 0; i < aParam.length; i++) {
if (aParam[i].substr(0, aParam[i].indexOf("=")).toLowerCase() == para.toLowerCase()) {
aParam[i] = aParam[i].substr(0, aParam[i].indexOf("=")) + "=" + val;
}
}
strNewUrl = url.substr(0, url.indexOf("?") + 1) + aParam.join("&");
window.location.href = strNewUrl;
}
} else {
strUrl += "?" + para + "=" + val;
window.location.href = strUrl;
}
}
二、利用正则
//使用正则
function setPara(para, val) {
var newpar = "";
var url = window.location.href;
var pars = location.search.substring(1);
var reg = new RegExp("(^|)" + para + "=([^&]*)(|$)");
if (reg.test(pars)) { //有需要的参数para
var p1 = pars.split(para)[0]; //productID=100857&count=1&
var p2 = pars.split(para)[1]; //=75825&coupval=1.5&addressID=358&invoiceID=1245&invoiceName=jesse
if (p2.indexOf("&") > -1) {
var p3 = p2.split("&")[0];
if (p3 == "=" + val + "") {
return false;
}
newpar = p1 + para + '=' + val + '&' + (p2.split(p3))[1];
} else {
if (p1) {
newpar = p1 + para + '=' + val;
} else {
newpar = para + '=' + val;
}
}
} else {
if (url.indexOf("?") == -1) {
newpar = pars +"&"+ para + "=" + val;
} else {
newpar = pars + "&" + para + "=" + val;
}
}
window.location.href = location.href.split('?')[0] + "?" + newpar;
}
调用:
<script>
window.onload = function () {
var btn = document.getElementById("btnClick");
btn.onclick = function () {
// url地址:http://localhost:54714/testuri.aspx?productID=100857&count=1&coupresId=12785&coupval=1.5&openId=12456&addressID=358&invoiceID=&invoiceName=
//setUri("coupresId", 0);
setPara("coupresId", 0);
}
}
</script>
<input type="button" id="btnClick" value="重定义参数" />
总结
以上是 JavaScript重定向URL参数的两种方法小结 的全部内容, 来源链接: utcz.com/z/340255.html