Skip to content

Instantly share code, notes, and snippets.

@nicksteffens
Created February 25, 2014 17:52
Show Gist options
  • Save nicksteffens/9214177 to your computer and use it in GitHub Desktop.
Save nicksteffens/9214177 to your computer and use it in GitHub Desktop.
JS window.location.search parse
// parse location.search
if(!window.location.query) {
window.location.query = function(){
var map = {};
if ("" != this.search) {
var groups = this.search.substr(1).split("&"), i;
for (i in groups) {
i = groups[i].split("=");
map[decodeURIComponent(i[0])] = decodeURIComponent(i[1]);
}
}
return map;
};
}
@kalisjoshua
Copy link

Love the idea of using Object.fromEntries here is my take hope it helps someone.

function parseSearch (str = "") {
  const pairs = str
  	.replace(/^\?/, "")
  	.split("&")
  	.filter(Boolean)
  	.map((pair) => {
      const [key, value = ""] = pair.split("=")

      return [
        key,
        value.includes(",")
          ? value.split(",").map((v) => v.trim())
          : value
			]
    })
  
  return Object.fromEntries(pairs)
}

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