4
8

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 5 years have passed since last update.

JavaScriptでGETパラメータを取得するワンライナー

Last updated at Posted at 2016-11-30

読みやすくするために改行しています。
ちゃんとしたワンライナー(;無し)になったのは2だけです。
(もうちょっと頑張れるのかも知れませんが…)

ES2015版の動作確認は Firefox 50.0, Chrome 54.0.2840.98 で行いました。

1. ES2015

window.location.search.substring(1).split('&')
  .reduce((result, query) => {
    const [k, v] = query.split('=');
    result[k] = decodeURI(v);
    return result;
  }, {});

2. ES2015 (Object.assignを使ったバージョン)

window.location.search.substring(1).split('&')
  .map(query => query.split('='))
  .reduce((result, [k, v]) => Object.assign(result, { [k]: decodeURI(v) }), {});

3. ES5

window.location.search.substring(1).split('&')
  .reduce(function(result, query) {
    var pair = query.split('=');
    result[pair[0]] = decodeURI(pair[1]);
    return result;
  }, {});

使い方

// ES2015
const getUrlParams = () => window.location.search.substring(1).split('&').reduce((result, query) => { const [k, v] = query.split('='); result[k] = decodeURI(v); return result; }, {});
//ES5
var getUrlParams = function() {
  return window.location.search.substring(1).split('&').reduce(function(result, query) { var pair = query.split('='); result[pair[0]] = decodeURI(pair[1]); return result; }, {});
}
getUrlParams();

実行結果

サンプルURL

結果

{ 
  site: "",
  source: "hp",
  q: "あいう+えお",
  oq: "あいう+えお"
}
4
8
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
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?