如何将URL参数转换为JavaScript对象?

编程入门 行业动态 更新时间:2024-10-23 10:28:58
本文介绍了如何将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对象?

本文发布于:2023-11-01 12:31:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   对象   参数   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!