LoginSignup
1
1

More than 5 years have passed since last update.

JavaScriptで'key=value&key2=value2…'StringをObejctに変換するには

Posted at

存外標準機能でついていなくて、
jquery - Convert URL parameters to a JavaScript object - Stack Overflow
を使う。

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

別解もあるらしく、

JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

微妙に変換される文字列が違う。
ひとまずURLエンコードされは文字列は必要なかったので、最初のものをdecodeURIComponentに変えた

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

を使うこととする。

1
1
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
1
1