Created
November 16, 2013 16:13
-
-
Save ssut/7502027 to your computer and use it in GitHub Desktop.
Query string access in javascript
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
function setGetParam() { | |
var url = arguments[2] || location.href; | |
if (arguments[0] instanceof Object) { // hash object | |
for(var arg in arguments[0]) { | |
if (!arg || !arguments[0][arg]) continue; | |
url = setGetParam(arg, arguments[0][arg], url); | |
} | |
} else if (typeof arguments[0] === 'string' && arguments[1]) { | |
paramName = arguments[0]; | |
paramValue = arguments[1]; | |
if (url.indexOf(paramName + '=') >= 0) { | |
var prefix = url.substring(0, url.indexOf(paramName)); | |
var suffix = url.substring(url.indexOf(paramName)).substring(url.indexOf('=') + 1); | |
suffix = (suffix.indexOf('&') >= 0) ? suffix.substring(suffix.indexOf('&')) : ''; | |
url = prefix + paramName + '=' + paramValue + suffix; | |
} else { | |
if (url.indexOf('?') < 0) | |
url += '?' + paramName + '=' + paramValue; | |
else | |
url += '&' + paramName + '=' + paramValue; | |
} | |
if (arguments[2]) return url; | |
} | |
if (url != location.href) { | |
location.href = url; | |
} | |
} | |
function getParam(name) { | |
return decodeURI( | |
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment