Skip to content

Instantly share code, notes, and snippets.

@IceCreamYou
Created June 20, 2015 03:33
Show Gist options
  • Save IceCreamYou/c9cfd398c75f0a257ea0 to your computer and use it in GitHub Desktop.
Save IceCreamYou/c9cfd398c75f0a257ea0 to your computer and use it in GitHub Desktop.
Updates a URL query parameter (or adds it if it doesn't already exist). Useful with history.pushState() / history.replaceState().
/**
* Create or update the value of a URL query parameter.
*
* Given an input URL, a query parameter, and a value, if the query parameter
* already exists in the URL, this function replaces that paramter's value with
* the given value; otherwise, this function adds the parameter to the URL and
* sets it to the given value. Returns the modified URL.
*/
function updateQueryParam(url, param, value) {
var search = new RegExp('([?&])(' + param + ')=[^&]*|$', 'i');
return url.replace(search, function(m, p1, p2, o, s) {
return (p1 ? p1 : (s.indexOf('?') === -1 ? '?' : '&')) + (p2 ? p2 : param) + '=' + value;
});
}
// Tests ======================================================================
// Test cases: original => replacement
var urls = {
'index.html': 'index.html?param=ABC',
'index.html?param=XYZ': 'index.html?param=ABC',
'index.html?PARAM=XYZ': 'index.html?PARAM=ABC',
'index.html?param=XYZ&a=1': 'index.html?param=ABC&a=1',
'index.html?a=1&param=XYZ': 'index.html?a=1&param=ABC',
'index.html?a=1&param=XYZ&b=2': 'index.html?a=1&param=ABC&b=2',
'index.html?param=': 'index.html?param=ABC',
'index.html?param=&a=1': 'index.html?param=ABC&a=1',
'index.html?a=1&param=': 'index.html?a=1&param=ABC',
'index.html?a=1&param=&b=2': 'index.html?a=1&param=ABC&b=2',
'index.html?a=1': 'index.html?a=1&param=ABC',
'index.html?a=1&b=2': 'index.html?a=1&b=2&param=ABC',
'index.html?params=XYZ': 'index.html?params=XYZ&param=ABC',
'index.html?a=1&params=XYZ&b=2': 'index.html?a=1&params=XYZ&b=2&param=ABC',
'index.html?aparam=XYZ': 'index.html?aparam=XYZ&param=ABC',
'index.html?a=1&aparam=XYZ&b=2': 'index.html?a=1&aparam=XYZ&b=2&param=ABC',
'index.html?a=1&aparams=XYZ&b=2': 'index.html?a=1&aparams=XYZ&b=2&param=ABC',
};
// Run tests
var s = 0, // success counter
f = 0; // failure counter
for (var prop in urls) {
if (urls.hasOwnProperty(prop)) {
var u = updateQueryParam(prop, 'param', 'ABC');
if (u !== urls[prop]) {
console.log(prop, urls[prop], u);
f++;
}
else {
s++;
}
}
}
console.log(s + ' test' + (s === 1 ? '' : 's') + ' ran successfully\n' + f + ' test' + (f === 1 ? '' : 's') + ' failed');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment