Kode
Ini Intinya oleh Eldon McGuinness ini sejauh ini merupakan implementasi paling lengkap dari parser string kueri JavaScript yang pernah saya lihat sejauh ini.
Sayangnya, ini ditulis sebagai plugin jQuery.
Saya menulis ulang ke vanilla JS dan membuat beberapa perbaikan:
function parseQuery(str) {
var qso = {};
var qs = (str || document.location.search);
// Check for an empty querystring
if (qs == "") {
return qso;
}
// Normalize the querystring
qs = qs.replace(/(^\?)/, '').replace(/;/g, '&');
while (qs.indexOf("&&") != -1) {
qs = qs.replace(/&&/g, '&');
}
qs = qs.replace(/([\&]+$)/, '');
// Break the querystring into parts
qs = qs.split("&");
// Build the querystring object
for (var i = 0; i < qs.length; i++) {
var qi = qs[i].split("=");
qi = qi.map(function(n) {
return decodeURIComponent(n)
});
if (typeof qi[1] === "undefined") {
qi[1] = null;
}
if (typeof qso[qi[0]] !== "undefined") {
// If a key already exists then make this an object
if (typeof (qso[qi[0]]) == "string") {
var temp = qso[qi[0]];
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]] = [];
qso[qi[0]].push(temp);
qso[qi[0]].push(qi[1]);
} else if (typeof (qso[qi[0]]) == "object") {
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]].push(qi[1]);
}
} else {
// If no key exists just set it as a string
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]] = qi[1];
}
}
return qso;
}
Bagaimana cara menggunakannya
var results = parseQuery("?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab");
Keluaran
{
"foo": ["bar", "boo" ],
"roo": "bar",
"bee": "bop",
"": ["ghost", "ghost2"],
"checkbox[]": ["b1", "b2"],
"dd": null,
"http": [
"http://w3schools.com/my test.asp?name=ståle&car=saab",
"http://w3schools2.com/my test.asp?name=ståle&car=saab"
]
}
Lihat juga Biola ini .