5
3

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

JavaScriptでリクエストパラメータをオブジェクトに変換する

Last updated at Posted at 2020-02-17

コピペで使えます


function convParamToObj() {
  var search = location.search.substring(1);
  if (search) {
    return JSON.parse('{"' + decodeURI(search.replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}')
  }
  return {};
}

追記

IEに対応させる必要がなければ、 URL.searchParams を使用すればシンプルに操作できます!

var params = (new URL(document.location)).searchParams;
var hoge = params.get('hoge'); // hoge
var fuga = params.get('fuga'); // fuga

それぞれの説明


var search = location.search.substring(1);
location.search // ?hoge=hoge&fuga=fuga
location.search.substring(1) // hoge=hoge&fuga=fuga

リクエストパラメータを取得しています

return JSON.parse('{"' + decodeURI(search.replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}')

ここは細かく確認します

search.replace(/&/g, "\",\"") // すべての & を "," に置換
search.replace(/=/g, "\":\"") // すべての = を ":" に置換
search.replace(/&/g, "\",\"").replace(/=/g, "\":\"")

正規表現を用いて、リクエストパラメータを下記のように置換しています

hoge=hoge&fuga=fuga
:point_down:
hoge":"hoge","fuga":"fuga

decodeURI(search.replace(/&/g, "\",\"").replace(/=/g, "\":\""))

リクエストパラメータがエスケープされている場合、文字列をデコードするためにdecodeURIを使用しています

'{"' + decodeURI(search.replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}'

{" と "} で先ほどの文字列を挟むとJSONの形になりますね!
hoge":"hoge","fuga":"fuga
:point_down:
{"hoge":"hoge","fuga":"fuga"}

JSON.parse('{"' + decodeURI(search.replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}')

最後にJSON.parseでJSONをオブジェクトに変換します

これでリクエストパラメータからオブジェクトへの変換ができました! :clap:

参考:
https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object

5
3
2

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?