Created
June 20, 2015 03:33
-
-
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().
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
/** | |
* 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¶m=XYZ': 'index.html?a=1¶m=ABC', | |
'index.html?a=1¶m=XYZ&b=2': 'index.html?a=1¶m=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¶m=': 'index.html?a=1¶m=ABC', | |
'index.html?a=1¶m=&b=2': 'index.html?a=1¶m=ABC&b=2', | |
'index.html?a=1': 'index.html?a=1¶m=ABC', | |
'index.html?a=1&b=2': 'index.html?a=1&b=2¶m=ABC', | |
'index.html?params=XYZ': 'index.html?params=XYZ¶m=ABC', | |
'index.html?a=1¶ms=XYZ&b=2': 'index.html?a=1¶ms=XYZ&b=2¶m=ABC', | |
'index.html?aparam=XYZ': 'index.html?aparam=XYZ¶m=ABC', | |
'index.html?a=1&aparam=XYZ&b=2': 'index.html?a=1&aparam=XYZ&b=2¶m=ABC', | |
'index.html?a=1&aparams=XYZ&b=2': 'index.html?a=1&aparams=XYZ&b=2¶m=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