本文介绍了如何将 URL 参数转换为 JavaScript 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的字符串:
I have a string like this:
abc=foo&def=%5Basf%5D&xyz=5
如何将其转换为这样的 JavaScript 对象?
How can I convert it into a JavaScript object like this?
{
abc: 'foo',
def: '[asf]',
xyz: 5
}
推荐答案
2021 年...请考虑完成.
编辑
此编辑根据评论改进并解释了答案.
In the year 2021... Please consider this ondone.
Edit
This edit improves and explains the answer based on the comments.
var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
示例
分五步解析abc=foo&def=%5Basf%5D&xyz=5
:
- decodeURI:abc=foo&def=[asf]&xyz=5
- 转义引号:相同,因为没有引号
- 替换 &:
abc=foo","def=[asf]","xyz=5
- Replace =:
abc":"foo","def":"[asf]","xyz":"5
- 用卷曲和引号环绕:
{"abc":"foo","def":"[asf]","xyz":"5"}
这是合法的 JSON.
which is legal JSON.
改进的解决方案允许在搜索字符串中包含更多字符.它使用一个 reviver 函数进行 URI 解码:
An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:
var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
示例
search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";
给予
Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}
原答案
单线:
JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "","").replace(/=/g,"":"")) + '"}')
这篇关于如何将 URL 参数转换为 JavaScript 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!