本文介绍了如何将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 }推荐答案
编辑
此修改根据评论进行了改进并解释了答案.
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
- 替换=:abc":"foo","def":"[asf]","xyz":"5
- 周围带有小圆括号和引号:{"abc":"foo","def":"[asf]","xyz":"5"}
- decodeURI: abc=foo&def=[asf]&xyz=5
- Escape quotes: same, as there are no quotes
- Replace &: abc=foo","def=[asf]","xyz=5
- Replace =: abc":"foo","def":"[asf]","xyz":"5
- Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}
这是合法的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对象?
发布评论