?hoi=1&hohoi=2
みたいなクエリストリングを、
{ hoi: "1", hohoi: "2" }
的なオブジェクトに変換するスクリプトです。
逆に、
{ hoi: "1", hohoi: "2" }
的なオブジェクトを、
hoi=1&hohoi=2
に変換することもできます。(あえて先頭に?はつけていません)
JavaScript
(function (win, doc) { "use strict"; function convertQueryToObject() { var obj = {}, query = location.search, params = query.split(/[?&]/), p, key, val; for (var i = 0, len = params.length; i < len; ++i) { p = params[i].split("="); key = normalize(p[0]); val = normalize(p[1]); if (key) { obj[key] = val; } } return obj; } function buildQueryString(obj) { var query = "", key, val; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } val = obj[key]; query += (query === "") ? "" : "&"; query += fixedEncodeURIComponent(key) + "="; if (val != null) { query += fixedEncodeURIComponent(val); } } return query; } function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A"); } function fixedDecodeURIComponent(str) { return decodeURIComponent(str.replace(/[!'()*]/g, unescape)); } function normalize(arg) { return (!arg) ? null : fixedDecodeURIComponent(arg); } })(this, document);
convertQueryToObjectを実行すると、location.searchをオブジェクトに変換します。
逆にbuildQueryStringにオブジェクトを渡すとクエリストリングに変換します。
fixedEncodeURIComponent、fixedDecodeURIComponent に関しては こちらの記事 をご確認ください。