Last active
August 29, 2015 14:22
-
-
Save mwurzberger/7339ed15b780f55e891b to your computer and use it in GitHub Desktop.
JavasScript URL Param Manipulation
This file contains hidden or 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
// Based on results at http://jsperf.com/url-param-manipulation | |
// setURLParam returns a new queryString but not an entire URL | |
testURL: 'https://www.test.com?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty&zpac=gooberface234324&a=3&b=4&c=5&d=11&e=15', | |
setURLParam: function( paramName, paramValue, urlString ) { | |
setURLParam: function( paramName, paramValue, urlString ) { | |
var urlParams = this.getURLParams( urlString ), | |
newParams = [], | |
foundParam = false; | |
for (var param in urlParams) { | |
if (param === paramName) { | |
newParams.push([param, paramValue].join('=')); | |
foundParam = true; | |
} else { | |
newParams.push([param, urlParams[param]].join('=')); | |
} | |
} | |
if( !foundParam ) { | |
newParams.push([paramName, paramValue].join('=')); | |
} | |
return newParams.join('&'); | |
}, | |
}, | |
getURLParam: function( paramName, urlString ) { | |
var match, | |
pl = /\+/g, // Regex for replacing addition symbol with a space | |
search = /([^&=]+)=?([^&]*)/g, | |
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, | |
query = urlString || window.location.search.substring(1); | |
urlParams = {}; | |
while ( match = search.exec( query ) ) { | |
if( paramName === decode( match[ 1 ] ) ) { | |
return decode( match[ 2 ] ); | |
} | |
} | |
return false; | |
}, | |
getURLParams: function( urlString ) { | |
var match, | |
pl = /\+/g, // Regex for replacing addition symbol with a space | |
search = /([^&=]+)=?([^&]*)/g, | |
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, | |
query = urlString || window.location.search.substring(1); | |
urlParams = {}; | |
while ( match = search.exec( query ) ) { | |
urlParams[ decode( match[ 1 ] ) ] = decode( match[ 2 ] ); | |
} | |
return urlParams; | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment