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

时间:2018-04-27 17:45:34

标签: javascript arrays parsing url query-string

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

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

然后它返回: parameters = [“product = shoes”,“price = 59.99”,“color = red”];

有什么建议吗?

谢谢,

2 个答案:

答案 0 :(得分:1)

根据您的浏览器要求,您可以使用 public requestList(): Observable<Record[]> { if (this.currentList !== undefined) { // MAGIC HERE: returning content that's already in this.currentList HOW? } return this.http.get(this.requestUrl) .map((response: any) => this.currentList = response.json()) .catch(this.setError); } 对象:

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

URLSearchParams

或者,如果您需要手动执行此操作,则可以拆分var params = new URLSearchParams(location.search); 字符串:

location.search

答案 1 :(得分:0)

您可以使用String的.slice().split()方法:

&#13;
&#13;
let str = 'http://example.com?product=shoes&price=59.99&color=red';

let parser = url => url.slice(url.indexOf('?') + 1).split('&');
               
console.log(parser(str));
&#13;
&#13;
&#13;

您还可以使用.reduce()

创建具有键/值对的对象

&#13;
&#13;
let str = 'http://example.com?product=shoes&price=59.99&color=red';

let parser = url => url.slice(url.indexOf('?') + 1)
                       .split('&')
                       .reduce((a, c) => {
                         let [key, value] = c.split('=');
                         a[key] = value;
                         return a;
                       }, {});

console.log(parser(str));
&#13;
&#13;
&#13;

<强>文档:

相关问题