LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptでGETパラメータ(URIクエリ)を取得する方法(コードスニペット)

Last updated at Posted at 2020-10-27

サンプルのクエリ:

?a=0&b=2&a=1&d[]=0&d[]=1&こんにちは=hoge=piyo

値にイコールが含まれてることと配列を考慮しない

const $_GET = Object.fromEntries(decodeURIComponent(location.search).slice(1).split('&').map(prop => prop.split('=')));

結果:

{
  "a": "1",
  "b": "2",
  "d[]": "1",
  "こんにちは": "hoge"
}

配列を考慮しない

const $_GET = Object.fromEntries(location.search.slice(1).split('&').map(prop => {
    const data = prop.split('=');

    return [data[0], decodeURIComponent(data.slice(1).join('='))]
}));

結果:

{
  "a": "1",
  "b": "2",
  "d[]": "1",
  "こんにちは": "hoge=piyo"
}

配列も考慮する

const $_GET = (query => {
    const dataSet = {};

    for (const data of query) {
        const key = data[0];
        const val = decodeURIComponent(data.slice(1).join('='));

        if (!key) {
            continue;
        }

        if (key.endsWith('[]')) {
            const _key = key.slice(0, -2);

            dataSet[_key] ??= [];
            dataSet[_key].push(val);

            continue;
        }

        dataSet[key] = val;
    }

    return dataSet;
})(location.search.slice(1).split('&').map(prop => prop.split('=')));

結果:

{
  "a": "1",
  "b": "2",
  "d": [
    "0",
    "1"
  ],
  "こんにちは": "hoge=piyo"
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0