js操作url的常用函数

1. //替换指定传入参数的值,paramName为参数,replaceWith为新值
function replaceParamVal(oUrl,paramName, replaceWith) {
var re = eval('/(' + paramName + '=)([^&]*)/gi');
var nUrl = oUrl.replace(re, paramName + '=' + replaceWith);
return nUrl;
}

2.//向URL中添加参数,如果参数存在替换参数的值

function UpdateUrlWithParam(url, key, value) {
var retUrl = url;

if (retUrl.indexOf("?") == -1) {
retUrl += "?" + key + "=" + value;
}
else {
if (retUrl.indexOf("&" + key + "=") == -1) {
if (retUrl.indexOf("?" + key + "=") == -1)
retUrl += "&" + key + "=" + value;
else
retUrl = retUrl.replace(eval('/(' + key + '=)([^&]*)/gi'), "?" + key + "=" + value);
} else {
retUrl = retUrl.replace(eval('/(' + key + '=)([^&]*)/gi'), "&" + key + "=" + value);
}
}
return retUrl;
}

3.//得到url里参数的值

function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}

原文地址:https://www.cnblogs.com/chenjt/p/5183962.html