Created
August 21, 2014 17:38
-
-
Save vermilion1/af0a9acbcd24edcdc82c to your computer and use it in GitHub Desktop.
Update search parameter
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 param value of the passed URI. | |
* In case parameter wasn't found we have to add it. | |
* @param {string} uri - URI. | |
* @param {string} key - Parameter name. | |
* @param {string} value - Parameter value. | |
* @returns {string} Updated URI. | |
*/ | |
var updateQueryStringParameter = function (uri, key, value) { | |
var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i'); | |
var hasSearch = uri.indexOf('?') !== -1; | |
var separator = hasSearch ? '&' : '?'; | |
if (uri.match(re)) { | |
return uri.replace(re, '$1' + key + '=' + value + '$2'); | |
} else { | |
var split = uri.split('#'); | |
var hash = split[1]; | |
return split[0] + separator + key + '=' + value + (hash ? '#' + hash : ''); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment