Created
February 25, 2014 17:52
-
-
Save nicksteffens/9214177 to your computer and use it in GitHub Desktop.
JS window.location.search parse
This file contains 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
// 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; | |
}; | |
} |
//some more corrections. Thanks for idea!
if ( !window.location.query ) {
window.location.query = () => Object.fromEntries(window.location.search.substr(1).split("&").map( group => group.split("=")));
}
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
some corrections
// parse location.search
if(!window.location.query) {
window.location.query = function(){
var map = {};
};
}