-
-
Save stinoga/8101816 to your computer and use it in GitHub Desktop.
// 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; | |
} |
@slaveofcode Nice work. You might want to update to do a case-insensitive match, otherwise it will duplicate the parameters to the resulting string. Minor update, but overall a great solution.
var re = new RegExp("[\\?&]" + param + "=([^&#]*)", "i"), match = re.exec(url), delimiter, newString;
Using this thread I have compiled a String prototype to easily replace params in a URL enjoy.
// Replace or add parameters to a url
// Author: James Bernard
// email: [email protected]
// Version: 0.5
String.prototype.replaceParam = function(paramsObject, add)
{
var originalUrl = this.toString();
var params = Object.keys(paramsObject);
var newUrl = originalUrl;
params.forEach(function(param){
// Author: iratherscribble@gitHub
var re = new RegExp("[\\?&]" + param + "=([^&#]*)", "i"), match = re.exec(newUrl), delimiter, newString;
// =============
// Author: slaveofcode@gitHub
if (match === null && add) {
// append new param
var hasQuestionMark = /\?/.test(url);
delimiter = hasQuestionMark ? "&" : "?";
newUrl = newUrl + delimiter + param + "=" + paramsObject[param];
} else if(match){
delimiter = match[0].charAt(0);
newUrl = newUrl.replace(re, delimiter + param + "=" + paramsObject[param]);
} else {
console.error("Parameter", "'" + param + "'", "Does not exist in url: ", originalUrl);
console.error("To add these parameters to this url please change your method call to: replaceParam([Object], [Boolean=true])")
}
})
return newUrl;
}
Patched this to work with urls that contain ?: or &: in their parameters.
// Replace or add parameters to a url
// Author: James Bernard
// email: [email protected]
// Version: 0.6
String.prototype.replaceParam = function(paramsObject, add)
{
var originalUrl = this.toString();
var params = Object.keys(paramsObject);
var newUrl = originalUrl;
params.forEach(function(param){
// Author: iratherscribble@gitHub
var re = new RegExp("[\\?&:]" + param + "=([^&#]*)", "i"), match = re.exec(newUrl), delimiter, newString;
// =============
// Author: slaveofcode@gitHub
if (match === null && add) {
// append new param
var hasQuestionMark = /\?/.test(url);
var hasColon = /\:/.test(url);
delimiter = hasColon ? (hasQuestionMark ? "&:" : "?:") : (hasQuestionMark ? "&" : "?");
newUrl = newUrl + delimiter + param + "=" + paramsObject[param];
} else if(match){
delimiter = match[0].charAt(0);
newUrl = newUrl.replace(re, delimiter + param + "=" + paramsObject[param]);
} else {
console.error("Parameter", "'" + param + "'", "Does not exist in url: ", originalUrl);
console.error("To add these parameters to this url please change your method call to: replaceParam([Object], [Boolean=true])")
}
})
return newUrl;
}
@jbernard1: Thanks for the code! Noticed that these two lines:
var hasQuestionMark = /\?/.test(url);
var hasColon = /\:/.test(url);
Should be:
var hasQuestionMark = /\?/.test(newUrl);
var hasColon = /\:/.test(newUrl);
Cheers! :)
This is my preference, and it covers the cases I can think of. Can anyone think of a way to reduce it to a single replace?
function setParam(uri, key, val) {
return uri
.replace(new RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
.replace(/^([^?&]+)&/, "$1?");
}
/**
- 替换url参数
- @param {String} name 参数名
- @param {String} value 参数值
- @param {String} url 如果该值存在,则以该值为基准替换
/
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
To replace all the query parameters with given value you can use something like this:
url.replace(/([?&])(((?![?&#=]).)*=)((?![?&#=]).)*/g, '$1$2xxx');
I think this is better
This function will add new parameter if not exist before, and will replace the old one if exist, without messing with any of existing querystring parameters.
to use
var newUrl = queryStringUrlReplacement('http://www.tomatmerah.com/', 'page', '18');