Last active
August 29, 2015 14:14
-
-
Save jonathanconway/02a183920506acd9890a to your computer and use it in GitHub Desktop.
Add a query parameter and value to a given URL string
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
// Usage: | |
// | |
// ('http://www.example.com').withParam('foo', 'bar'); | |
// -> http://www.example.com?foo=bar | |
// | |
// ('http://www.example.com').withParam('foo'); | |
// -> http://www.example.com?foo | |
// | |
// Credit: Lessan Vaezi | |
// (See: http://stackoverflow.com/a/487084/23341) | |
String.prototype.withParam = function (name, value){ | |
var url = this, | |
parameterName = name, | |
parameterValue = value || '', | |
atStart, | |
cl, | |
urlParts, | |
urlhash, | |
sourceUrl, | |
newQueryString, | |
parameters, | |
parameterParts, | |
i, | |
replaceDuplicates = true; | |
if (url.indexOf('#') > 0) { | |
cl = url.indexOf('#'); | |
urlhash = url.substring(url.indexOf('#'),url.length); | |
} | |
else { | |
urlhash = ''; | |
cl = url.length; | |
} | |
sourceUrl = url.substring(0, cl); | |
urlParts = sourceUrl.split('?'); | |
newQueryString = ''; | |
if (urlParts.length > 1) { | |
parameters = urlParts[1].split('&'); | |
for (i = 0; (i < parameters.length); i++) { | |
parameterParts = parameters[i].split('='); | |
if (!(replaceDuplicates && parameterParts[0] === parameterName)) { | |
if (newQueryString === '') | |
newQueryString = '?'; | |
else | |
newQueryString += '&'; | |
newQueryString += parameterParts[0] + '=' + (parameterParts[1] ? parameterParts[1] : ''); | |
} | |
} | |
} | |
if (newQueryString === '') | |
newQueryString = '?'; | |
if (newQueryString !== '' && newQueryString != '?') | |
newQueryString += '&'; | |
newQueryString += parameterName + '=' + (parameterValue ? parameterValue : ''); | |
return urlParts[0] + newQueryString + urlhash; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment