Created
November 19, 2012 01:13
-
-
Save DFrenkel/4108452 to your computer and use it in GitHub Desktop.
JS urlFor
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
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