解析URL 获取query参数值的两种方法

方法有2,根据实际开发需求选择

let url = '/pages/product/detail/index?visitStore=35603523&mdCode=9100000890&productId=27451'

方法一

将url的string字符串解析为数组:

getQueryArray(url) {
    let query = url.split("?").pop().split("&");
    let result = query.reduce(
        (total, cur) => {
            let tmpObj = {}
            let t = cur.split("=")
            tmpObj.name = t.shift()
            tmpObj.value = t.shift()
            total.push(tmpObj);
            return total
        },
        []
    )
    return (result)
  },
let arr = this.getQueryArray(visitStore);
console.log(arr)
输出值为数组:
    [
      {name: "visitStore", value: "35603523"},
      {name: "mdCode", value: "9100000890"},
      {name: "productId", value: "27451"}
    ]

方法二
直接根据已知name取value

getQueryVariable(variable, url){
    var str=url.split('?');
    var query=str[1];
    var vars=query.split('&');
    console.log(query,str,vars);
    for (var i=0;i

你可能感兴趣的:(解析URL 获取query参数值的两种方法)