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

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

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

发布评论

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

>www.elefans.com

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