Created
April 30, 2022 01:53
-
-
Save n8jadams/76c04dd487b070b15d47e16e808bfdca to your computer and use it in GitHub Desktop.
Parse query string. (Just use URLSearchParams instead of this)
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
function parseQueryString(query) { | |
query = query.substring(query.indexOf('?') + 1); | |
let re = /([^&=]+)=?([^&]*)/g; | |
let decodeRE = /\+/g; | |
let decode = function(str) { | |
return decodeURIComponent(str.replace(decodeRE, ' ')); | |
}; | |
let params = {}, | |
e; | |
while ((e = re.exec(query))) { | |
let k = decode(e[1]), | |
v = decode(e[2]); | |
if (k.substring(k.length - 2) === '[]') { | |
k = k.substring(0, k.length - 2); | |
(params[k] || (params[k] = [])).push(v); | |
} else params[k] = v; | |
} | |
let assign = function(obj, keyPath, value) { | |
let lastKeyIndex = keyPath.length - 1; | |
for (let i = 0; i < lastKeyIndex; ++i) { | |
let key = keyPath[i]; | |
if (!(key in obj)) obj[key] = {}; | |
obj = obj[key]; | |
} | |
obj[keyPath[lastKeyIndex]] = value; | |
}; | |
for (let prop in params) { | |
let structure = prop.split('['); | |
if (structure.length > 1) { | |
let levels = []; | |
structure.forEach(function(item, i) { | |
let key = item.replace(/[?[\]\\ ]/g, ''); | |
levels.push(key); | |
}); | |
assign(params, levels, params[prop]); | |
delete params[prop]; | |
} | |
} | |
return params; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment