Last active
January 22, 2021 12:47
-
-
Save blakek/660a8881ae56641d8804971b848df17e to your computer and use it in GitHub Desktop.
Parse query string in browser (<=ES5)
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
// Deserialize query string to object | |
// Example: var queryParams = queryStringParse(window.location.search) | |
function queryStringParse (str) { | |
var ret = Object.create(null) | |
if (typeof str !== 'string') { | |
return ret | |
} | |
str = str.trim().replace(/^(\?|#|&)/, '') | |
if (!str) { | |
return ret | |
} | |
str.split('&').forEach(function (param) { | |
var parts = param.replace(/\+/g, ' ').split('=') | |
// Firefox (pre 40) decodes `%3D` to `=` | |
// https://github.com/sindresorhus/query-string/pull/37 | |
var key = parts.shift() | |
var val = parts.length > 0 ? parts.join('=') : undefined | |
key = decodeURIComponent(key) | |
// missing `=` should be `null`: | |
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters | |
val = val === undefined ? null : decodeURIComponent(val); | |
if (ret[key] === undefined) { | |
ret[key] = val | |
} else if (Array.isArray(ret[key])) { | |
ret[key].push(val) | |
} else { | |
ret[key] = [ret[key], val] | |
} | |
}) | |
return ret | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment