22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptでURLクエリを取得する

Last updated at Posted at 2018-07-09

クエリ文字列の取得は

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;
}

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

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

22
17
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
22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?