Skip to content

Instantly share code, notes, and snippets.

@codebubb
Created April 15, 2016 13:31
Show Gist options
  • Select an option

  • Save codebubb/0c93b706cf60f249e13f72eccdf921e5 to your computer and use it in GitHub Desktop.

Select an option

Save codebubb/0c93b706cf60f249e13f72eccdf921e5 to your computer and use it in GitHub Desktop.
function which takes a URL and extracts key/value pairs based on positions in array.
var parse_params = function(url){
var pairs = url.match(/\/?\??(.*)/)[1].split('&');
var out = [];
pairs.forEach(function(chunk){
var keyvalues = chunk.split('=');
for(var i=0; i<keyvalues.length; i++){
if(i % 2 === 0){
var obj = {};
obj[keyvalues[i]] = keyvalues[i + 1]
out.push(obj);
}
}
});
return out;
}
var url = "/?key=dfdsf&val=4535&name=james";
console.log(parse_params(url));
// [ { key: 'dfdsf' }, { val: '4535' }, { name: 'james' } ]
@codebubb
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment