Skip to content

Instantly share code, notes, and snippets.

@ergoithz
Last active August 11, 2016 10:02
Show Gist options
  • Save ergoithz/1af49e8db4c39c5df65121fda9f1118c to your computer and use it in GitHub Desktop.
Save ergoithz/1af49e8db4c39c5df65121fda9f1118c to your computer and use it in GitHub Desktop.
parse GET parameters from JS
function getParam(key, qs) {
const
results = [],
reg = new RegExp(`(^|\&)(${key})(=([^&]*))?($|\&)`);
let
match = reg.exec(qs = qs||document.location.search.substr(1));
while(match){
results.push(match[3]?decodeURIComponent(match[4].replace('+', ' ')):true);
match = reg.exec(qs = qs.substr(match.index + match[0].length - 1));
}
return results;
}
let
tests = [
'patata&pata=1&pata',
'patata&pa=2&pata=1&pata=2'
];
for(let test of tests){
console.log(getParam('pata', test));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment