我有一个这样的字符串:

abc=foo&def=%5Basf%5D&xyz=5

如何将其转换为这样的JavaScript对象?

{
  abc: 'foo',
  def: '[asf]',
  xyz: 5
}

当前回答

/** * Parses and builds Object of URL query string. * @param {string} query The URL query string. * @return {!Object<string, string>} */ function parseQueryString(query) { if (!query) { return {}; } return (/^[?#]/.test(query) ? query.slice(1) : query) .split('&') .reduce((params, param) => { const item = param.split('='); const key = decodeURIComponent(item[0] || ''); const value = decodeURIComponent(item[1] || ''); if (key) { params[key] = value; } return params; }, {}); } console.log(parseQueryString('?v=MFa9pvnVe0w&ku=user&from=89&aw=1')) see log

其他回答

这是一个简单的版本,显然你需要添加一些错误检查:

var obj = {};
var pairs = queryString.split('&');
for(i in pairs){
    var split = pairs[i].split('=');
    obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}
//under ES6 
const getUrlParamAsObject = (url = window.location.href) => {
    let searchParams = url.split('?')[1];
    const result = {};
    //in case the queryString is empty
    if (searchParams!==undefined) {
        const paramParts = searchParams.split('&');
        for(let part of paramParts) {
            let paramValuePair = part.split('=');
            //exclude the case when the param has no value
            if(paramValuePair.length===2) {
                result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
            }
        }

    }
    return result;
}

我发现$. string .deparam是最完整的预构建解决方案(可以做嵌套对象等)。查看文档。

下面是我用的一个例子:

var params = {};
window.location.search.substring(1).split('&').forEach(function(pair) {
  pair = pair.split('=');
  if (pair[1] !== undefined) {
    var key = decodeURIComponent(pair[0]),
        val = decodeURIComponent(pair[1]),
        val = val ? val.replace(/\++/g,' ').trim() : '';

    if (key.length === 0) {
      return;
    }
    if (params[key] === undefined) {
      params[key] = val;
    }
    else {
      if ("function" !== typeof params[key].push) {
        params[key] = [params[key]];
      }
      params[key].push(val);
    }
  }
});
console.log(params);

基本用法。 ? = aa&b = bb 对象{a: "aa", b: "bb"}

重复参数,例如。 ? = aa&b = bb&c = cc&c =土豆 对象{a: "aa", b: "bb", c: ["cc","potato"]}

钥匙不见了。 ? = aa&b = bb = cc 对象{a: "aa", b: "bb"}

缺少值,例如。 = aa&b = bb&c ? 对象{a: "aa", b: "bb"}

上述JSON/regex解决方案在这个古怪的url上抛出了一个语法错误: ? = aa&b = bb&c = & = dd&e 对象{a: "aa", b: "bb", c: ""}

如果你正在使用URI.js,你可以使用:

https://medialize.github.io/URI.js/docs.html#static-parseQuery

var result = URI.parseQuery("?foo=bar&hello=world&hello=mars&bam=&yup");
result === {
  foo: "bar",
  hello: ["world", "mars"],
  bam: "",
  yup: null
};