17
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

JavaScriptでURLクエリを取得する

クエリ文字列の取得は

window.location.search
=> "?foo=1&bar=2"

クエリ文字列をオブジェクトに整形する関数を用意。

function getUrlQueries() {
  var queryStr = window.location.search.slice(1);  // 文頭?を除外
      queries = {};

  // クエリがない場合は空のオブジェクトを返す
  if (!queryStr) {
    return queries;
  }

  // クエリ文字列を & で分割して処理
  queryStr.split('&').forEach(function(queryStr) {
    // = で分割してkey,valueをオブジェクトに格納
    var queryArr = queryStr.split('=');
    queries[queryArr[0]] = queryArr[1];
  });

  return queries;
}

これでめでたくクエリのオブジェクトの取得ができるようになりました🎉

ブログからの転載記事です。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
17
Help us understand the problem. What are the problem?