1
1

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で'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,'":"') + '"}')


別解もあるらしく、

>```js
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?