Skip to content

Instantly share code, notes, and snippets.

@DFrenkel
Created November 19, 2012 01:13
Show Gist options
  • Save DFrenkel/4108452 to your computer and use it in GitHub Desktop.
Save DFrenkel/4108452 to your computer and use it in GitHub Desktop.
JS urlFor
urlFor = function(url, params)
{
url = url || window.location.href || '';
url = url.match(/\?/) ? url : url + '?';
for (var key in params) {
var re1 = RegExp( '\\?' + key + '=[^\&$]*(&|$)', 'g' );
var re2 = RegExp( '\&' + key + '=[^\&$]*(&|$)', 'g' );
var replacement = params[key] ? key + '=' + params[key] : "";
if (re1.test(url)) {
url = url.replace(re1, '?' + replacement + '&')
}
else if (re2.test(url)) {
url = url.replace(re2, '&' + replacement + '&')
}
else {
url += '&' + replacement;
}
}
if (url.indexOf("?", url.length - 1) !== -1) {
url = url.substring(0, url.length - 1)
}
// cleanup url
url = url.replace(/\&*$/g, '');
url = url.replace(/\?\&*/g, '?');
url = url.replace(/[&]{2}/g, '&');
url = url.replace(/\?$/g, '');
return url;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment