我想构建一个函数,从当前 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/