javascript - 将 URL 查询字符串解析为数组

标签 javascript arrays parsing url query-string

我想构建一个函数,从当前 URL(例如 document.location)中解析 URL 查询字符串(参数和值),并将每个键值对(参数=值)存储为数组中的单个元素。

例如,如果 URL 是: http://example.com?product=shoes&price=59.99&color=red

然后返回: 参数 = ["产品=鞋子","价格=59.99","颜色=红色"];

有什么建议吗?

谢谢

最佳答案

根据您的浏览器要求,您可以使用 URLSearchParams 对象:

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

var params = new URLSearchParams(location.search);

或者,如果您需要手动执行此操作,则可以拆分 location.search 字符串:

var qs = location.search.replace('?', '');  // get querystring and remove question marks
var pairs = qs.split('&');                  // split on ampersand
var items = {};                             // declare object to store key/value pairs

// Loop through pairs and extract the key and the value (and append them to the object)
for (var i = 0; i < pairs.length; i++) {
    items[pairs[i].split('=')[0]] = pairs[i].split('=')[1];
}

console.log(items);

关于javascript - 将 URL 查询字符串解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50067694/

相关文章:

c# - C#中迭代器和数组的区别

java - 无法在 linux 上解析 xhtml 文档

解析挑战 : Old logician's dot notation

javascript - 在 AngularJS 中聚合对象

javascript - 使用正则表达式,有条件地替换为 $1 或空字符串

arrays - 使用 Postgres JSONB 查询查询数组中的数组

url - 一个 URL 中包含多个问号是否有效?

javascript - 如何使用 Node 服务器中的变量到另一个 javascript 文件中

javascript - 无法使用 for-in javascript 进行迭代

javascript - JSON 处理 - JavaScript