Created
December 23, 2013 18:05
-
-
Save stinoga/8101816 to your computer and use it in GitHub Desktop.
Replacing query string parameter values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Update the appropriate href query string parameter | |
function paramReplace(name, string, value) { | |
// Find the param with regex | |
// Grab the first character in the returned string (should be ? or &) | |
// Replace our href string with our new value, passing on the name and delimeter | |
var re = new RegExp("[\\?&]" + name + "=([^&#]*)"), | |
delimeter = re.exec(string)[0].charAt(0), | |
newString = string.replace(re, delimeter + name + "=" + value); | |
return newString; | |
} |
To replace all the query parameters with given value you can use something like this:
url.replace(/([?&])(((?![?&#=]).)*=)((?![?&#=]).)*/g, '$1$2xxx');
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/**
/
function replaceUrlParam(name, value, newUrl) {
let urlMark = '';
let url = newUrl || location.href;
let nameIndex = url.indexOf(name);
//删除参数
if (value === '') {
//取当前参数前一位字符
urlMark = url.charAt(nameIndex - 1);
if (!/?|&/.test(urlMark)) {
urlMark = '';
}
let reg = new RegExp("\" + urlMark + name + '=' + "[^&]");
url = url.replace(reg, '');
}
//如果一个参数都没有
else if (window.location.search === "" && new URL(location.href).searchParams.get(url) === '') {
urlMark = '?';
url = url + urlMark + name + '=' + value;
}
//有参数, 有当前参数
else if (nameIndex > -1) {
//这个urlMark 可能会是 ? 或 &
urlMark = url.charAt(nameIndex - 1);
let reg = new RegExp("\" + urlMark + name + '=' + "[^&]*");
url = url.replace(reg, urlMark + name + '=' + value);
}
//有参数,但没有当前参数
else if (nameIndex === -1) {
urlMark = '&';
url = url + urlMark + name + '=' + value;
}
//替换为正确的符号参数
if (url.indexOf('?') === -1) {
let matchParam = url.match('&');
if (matchParam !== null) {
url = url.replace(/&/, '?');
}
}
return url;
}
this is better