Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanconway/02a183920506acd9890a to your computer and use it in GitHub Desktop.
Save jonathanconway/02a183920506acd9890a to your computer and use it in GitHub Desktop.
Add a query parameter and value to a given URL string
// 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