将URL参数转换为JavaScript对象

时间:2011-12-27 20:19:38

标签: javascript jquery url url-parameters url-parsing

我有一个这样的字符串:

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

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

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

35 个答案:

答案 0 :(得分:278)

修改

此编辑会根据评论改进并解释答案。

var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

示例

分五个步骤解析abc=foo&def=%5Basf%5D&xyz=5

  • decodeURI:abc = foo& def = [asf]& xyz = 5
  • 转义引号:相同,因为没有引号
  • 替换&amp ;: abc=foo","def=[asf]","xyz=5
  • 替换=:abc":"foo","def":"[asf]","xyz":"5
  • 用曲线和引号进行描述:{"abc":"foo","def":"[asf]","xyz":"5"}

这是合法的JSON。

改进的解决方案允许搜索字符串中包含更多字符。它使用reviver函数进行URI解码:

var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

示例

search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";

给出

Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}

原始答案

单行:

JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')

答案 1 :(得分:32)

2018 ES6 / 7/8及更高版本

从ES6开始,Javascript提供了几种结构来创建针对此问题的高性能解决方案。

这包括使用URLSearchParamsiterators

let params = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
params.get("abc"); // "foo"

如果您的用例需要您将其实际转换为对象,则可以实现以下功能:

function paramsToObject(entries) {
  let result = {}
  for(let entry of entries) { // each 'entry' is a [key, value] tupple
    const [key, value] = entry;
    result[key] = value;
  }
  return result;
}

基本演示

const urlParams = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
const entries = urlParams.entries(); //returns an iterator of decoded [key,value] tuples
const params = paramsToObject(entries); //{abc:"foo",def:"[asf]",xyz:"5"}

使用Object.fromEntries并传播

我们可以使用Object.fromEntries(目前处于第4阶段),将paramsToObject替换为Object.fromEntries(entries)

由于URLParams返回iterable对象,所以使用spread operator而不是调用.entries也会按照其规范生成条目:

  

要迭代的值对是列表名称-值对,其中   键是名称,值是值。

const urlParams = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
const params = Object.fromEntries(...params); // {abc: "foo", def: "[asf]", xyz: "5"}

注意:根据URLSearchParams spec

,所有值都是自动字符串

答案 2 :(得分:24)

&上拆分以获取名称/值对,然后在=上拆分每对。这是一个例子:

var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
var obj = str.split("&").reduce(function(prev, curr, i, arr) {
    var p = curr.split("=");
    prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
    return prev;
}, {});

使用正则表达式的另一种方法:

var obj = {}; 
str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
    obj[decodeURIComponent(key)] = decodeURIComponent(value);
}); 

这是改编自John Resig的"Search and Don’t Replace"

答案 3 :(得分:13)

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

var obj = {};
var pairs = queryString.split('&');
for(i in pairs){
    var split = pairs[i].split('=');
    obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}

答案 4 :(得分:10)

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

答案 5 :(得分:9)

简明的解决方案:

location.search
  .slice(1)
  .split('&')
  .map(p => p.split('='))
  .reduce((obj, pair) => {
    const [key, value] = pair.map(decodeURIComponent);
    return ({ ...obj, [key]: value })
  }, {});

答案 6 :(得分:8)

另一种基于最新标准的URLSearchParams(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

的解决方案
function getQueryParamsObject() {
  const searchParams = new URLSearchParams(location.search.slice(1));
  return searchParams
    ? _.fromPairs(Array.from(searchParams.entries()))
    : {};
}

请注意,此解决方案正在使用

Array.from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

为了简单起见,lodash的

_。fromPairs https://lodash.com/docs#fromPairs)。

创建更兼容的解决方案应该很容易,因为您可以访问 searchParams.entries()迭代器。

答案 7 :(得分:7)

到目前为止我找到的建议解决方案并未涉及更复杂的情况。

我需要转换像

这样的查询字符串

https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name

进入像:

这样的对象
{
    "Target": "Offer",
    "Method": "findAll",
    "fields": [
        "id",
        "name",
        "default_goal_name"
    ],
    "filters": {
        "has_goals_enabled": {
            "TRUE": "1"
        },
        "status": "active"
    }
}

OR:

https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999

INTO:

{
    "Target": "Report",
    "Method": "getStats",
    "fields": [
        "Offer.name",
        "Advertiser.company",
        "Stat.clicks",
        "Stat.conversions",
        "Stat.cpa",
        "Stat.payout",
        "Stat.date",
        "Stat.offer_id",
        "Affiliate.company"
    ],
    "groups": [
        "Stat.offer_id",
        "Stat.date"
    ],
    "limit": "9999",
    "filters": {
        "Stat.affiliate_id": {
            "conditional": "EQUAL_TO",
            "values": "1831"
        }
    }
}

我将多个解决方案编译并调整为实际可行的解决方案:

CODE:

var getParamsAsObject = function (query) {

    query = query.substring(query.indexOf('?') + 1);

    var re = /([^&=]+)=?([^&]*)/g;
    var decodeRE = /\+/g;

    var decode = function (str) {
        return decodeURIComponent(str.replace(decodeRE, " "));
    };

    var params = {}, e;
    while (e = re.exec(query)) {
        var k = decode(e[1]), v = decode(e[2]);
        if (k.substring(k.length - 2) === '[]') {
            k = k.substring(0, k.length - 2);
            (params[k] || (params[k] = [])).push(v);
        }
        else params[k] = v;
    }

    var assign = function (obj, keyPath, value) {
        var lastKeyIndex = keyPath.length - 1;
        for (var i = 0; i < lastKeyIndex; ++i) {
            var key = keyPath[i];
            if (!(key in obj))
                obj[key] = {}
            obj = obj[key];
        }
        obj[keyPath[lastKeyIndex]] = value;
    }

    for (var prop in params) {
        var structure = prop.split('[');
        if (structure.length > 1) {
            var levels = [];
            structure.forEach(function (item, i) {
                var key = item.replace(/[?[\]\\ ]/g, '');
                levels.push(key);
            });
            assign(params, levels, params[prop]);
            delete(params[prop]);
        }
    }
    return params;
};

答案 8 :(得分:6)

我遇到了同样的问题,在这里尝试了解决方案,但是没有一个真正有用,因为我在URL参数中有数组,如下所示:

?param[]=5&param[]=8&othr_param=abc&param[]=string

所以我最终编写了自己的JS函数,它在URI中创建了一个数组:

/**
 * Creates an object from URL encoded data
 */
var createObjFromURI = function() {
    var uri = decodeURI(location.search.substr(1));
    var chunks = uri.split('&');
    var params = Object();

    for (var i=0; i < chunks.length ; i++) {
        var chunk = chunks[i].split('=');
        if(chunk[0].search("\\[\\]") !== -1) {
            if( typeof params[chunk[0]] === 'undefined' ) {
                params[chunk[0]] = [chunk[1]];

            } else {
                params[chunk[0]].push(chunk[1]);
            }


        } else {
            params[chunk[0]] = chunk[1];
        }
    }

    return params;
}

答案 9 :(得分:5)

ES6一个衬板(如果看到长线的话我们可以这样称呼)

[...new URLSearchParams(location.search).entries()].reduce((prev, [key,val]) => {prev[key] = val; return prev}, {})

答案 10 :(得分:5)

ES6单线。干净简单。

var obj = [...new URLSearchParams(location.search).entries()].reduce((sum, [key,val]) => Object.assign({[key]:val}, sum), {});

答案 11 :(得分:5)

使用URLSearchParam接口执行此操作的最简单方法之一。

下面是工作代码段:

let paramObj={},
    querystring=window.location.search,
    searchParams = new URLSearchParams(querystring);    

  //*** :loop to add key and values to the param object.
 searchParams.forEach(function(value, key) {
      paramObj[key] = value;
   });

答案 12 :(得分:5)

使用ES6,URL API和URLSearchParams API。

function objectifyQueryString(url) {
  let _url = new URL(url);
  let _params = new URLSearchParams(_url.search);
  let query = Array.from(_params.keys()).reduce((sum, value)=>{
    return Object.assign({[value]: _params.get(value)}, sum);
  }, {});
  return query;
}

答案 13 :(得分:2)

使用phpjs

function parse_str(str, array) {
  //       discuss at: http://phpjs.org/functions/parse_str/
  //      original by: Cagri Ekin
  //      improved by: Michael White (http://getsprink.com)
  //      improved by: Jack
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: Onno Marsman
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: stag019
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
  // reimplemented by: stag019
  //         input by: Dreamer
  //         input by: Zaide (http://zaidesthings.com/)
  //         input by: David Pesta (http://davidpesta.com/)
  //         input by: jeicquest
  //             note: When no argument is specified, will put variables in global scope.
  //             note: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
  //             test: skip
  //        example 1: var arr = {};
  //        example 1: parse_str('first=foo&second=bar', arr);
  //        example 1: $result = arr
  //        returns 1: { first: 'foo', second: 'bar' }
  //        example 2: var arr = {};
  //        example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
  //        example 2: $result = arr
  //        returns 2: { str_a: "Jack and Jill didn't see the well." }
  //        example 3: var abc = {3:'a'};
  //        example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
  //        returns 3: {"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}

  var strArr = String(str)
    .replace(/^&/, '')
    .replace(/&$/, '')
    .split('&'),
    sal = strArr.length,
    i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
    postLeftBracketPos, keys, keysLen,
    fixStr = function(str) {
      return decodeURIComponent(str.replace(/\+/g, '%20'));
    };

  if (!array) {
    array = this.window;
  }

  for (i = 0; i < sal; i++) {
    tmp = strArr[i].split('=');
    key = fixStr(tmp[0]);
    value = (tmp.length < 2) ? '' : fixStr(tmp[1]);

    while (key.charAt(0) === ' ') {
      key = key.slice(1);
    }
    if (key.indexOf('\x00') > -1) {
      key = key.slice(0, key.indexOf('\x00'));
    }
    if (key && key.charAt(0) !== '[') {
      keys = [];
      postLeftBracketPos = 0;
      for (j = 0; j < key.length; j++) {
        if (key.charAt(j) === '[' && !postLeftBracketPos) {
          postLeftBracketPos = j + 1;
        } else if (key.charAt(j) === ']') {
          if (postLeftBracketPos) {
            if (!keys.length) {
              keys.push(key.slice(0, postLeftBracketPos - 1));
            }
            keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
            postLeftBracketPos = 0;
            if (key.charAt(j + 1) !== '[') {
              break;
            }
          }
        }
      }
      if (!keys.length) {
        keys = [key];
      }
      for (j = 0; j < keys[0].length; j++) {
        chr = keys[0].charAt(j);
        if (chr === ' ' || chr === '.' || chr === '[') {
          keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
        }
        if (chr === '[') {
          break;
        }
      }

      obj = array;
      for (j = 0, keysLen = keys.length; j < keysLen; j++) {
        key = keys[j].replace(/^['"]/, '')
          .replace(/['"]$/, '');
        lastIter = j !== keys.length - 1;
        lastObj = obj;
        if ((key !== '' && key !== ' ') || j === 0) {
          if (obj[key] === undef) {
            obj[key] = {};
          }
          obj = obj[key];
        } else { // To insert new dimension
          ct = -1;
          for (p in obj) {
            if (obj.hasOwnProperty(p)) {
              if (+p > ct && p.match(/^\d+$/g)) {
                ct = +p;
              }
            }
          }
          key = ct + 1;
        }
      }
      lastObj[key] = value;
    }
  }
}

答案 14 :(得分:2)

我没有意识到的原生解决方案。如果您偶然使用该框架,Dojo有一个内置的反序列化方法。

否则你可以自己实现它:

function unserialize(str) {
  str = decodeURIComponent(str);
  var chunks = str.split('&'),
      obj = {};
  for(var c=0; c < chunks.length; c++) {
    var split = chunks[c].split('=', 2);
    obj[split[0]] = split[1];
  }
  return obj;
}

编辑:添加了decodeURIComponent()

答案 15 :(得分:2)

使用URLSearchParams JavaScript Web API

非常容易

var paramsString = "q=forum&topic=api";

//returns an iterator object
var searchParams = new URLSearchParams(paramsString);

//Usage
for (let p of searchParams) {
  console.log(p);
}

//Get the query strings
console.log(searchParams.toString());

//You can also pass in objects

var paramsObject = {q:"forum",topic:"api"}

//returns an iterator object
var searchParams = new URLSearchParams(paramsObject);

//Usage
for (let p of searchParams) {
  console.log(p);
}

//Get the query strings
console.log(searchParams.toString());

有用的链接

  

注意 IE不支持

答案 16 :(得分:2)

使用本机节点模块构建的一个简单答案。(无第三方npm模块)

querystring模块提供用于解析和格式化URL查询字符串的实用程序。可以使用以下方式访问它:

const querystring = require('querystring');

const body = "abc=foo&def=%5Basf%5D&xyz=5"
const parseJSON = querystring.parse(body);
console.log(parseJSON);

答案 17 :(得分:2)

/**
 * 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

答案 18 :(得分:2)

有一个名为YouAreI.js的轻量级库已经过测试,非常简单。

YouAreI = require('YouAreI')
uri = new YouAreI('http://user:pass@www.example.com:3000/a/b/c?d=dad&e=1&f=12.3#fragment');

uri.query_get() => { d: 'dad', e: '1', f: '12.3' }

答案 19 :(得分:1)

这似乎是最好的解决方案,因为它需要考虑多个相同名称的参数。

    function paramsToJSON(str) {
        var pairs = str.split('&');
        var result = {};
        pairs.forEach(function(pair) {
            pair = pair.split('=');
            var name = pair[0]
            var value = pair[1]
            if( name.length )
                if (result[name] !== undefined) {
                    if (!result[name].push) {
                        result[name] = [result[name]];
                    }
                    result[name].push(value || '');
                } else {
                    result[name] = value || '';
                }
        });
        return( result );
    }

<a href="index.html?x=1&x=2&x=3&y=blah">something</a>
paramsToJSON("x=1&x=2&x=3&y=blah"); 

console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON

我后来决定将它转换为jQuery插件......

$.fn.serializeURLParams = function() {
    var result = {};

    if( !this.is("a") || this.attr("href").indexOf("?") == -1 ) 
        return( result );

    var pairs = this.attr("href").split("?")[1].split('&');
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        var name = decodeURI(pair[0])
        var value = decodeURI(pair[1])
        if( name.length )
            if (result[name] !== undefined) {
                if (!result[name].push) {
                    result[name] = [result[name]];
                }
                result[name].push(value || '');
            } else {
                result[name] = value || '';
            }
    });
    return( result )
}

<a href="index.html?x=1&x=2&x=3&y=blah">something</a>
$("a").serializeURLParams(); 

console yields => {x: Array[3], y: "blah"} where x is an array as is proper JSON

现在,第一个只接受参数,但jQuery插件将获取整个url并返回序列化参数。

答案 20 :(得分:1)

如果需要递归,则可以使用小型的 js-extension-ling 库。

npm i js-extension-ling
const jsx = require("js-extension-ling");

console.log(jsx.queryStringToObject("a=1")); 
console.log(jsx.queryStringToObject("a=1&a=3")); 
console.log(jsx.queryStringToObject("a[]=1")); 
console.log(jsx.queryStringToObject("a[]=1&a[]=pomme")); 
console.log(jsx.queryStringToObject("a[0]=one&a[1]=five"));
console.log(jsx.queryStringToObject("http://blabla?foo=bar&number=1234")); 
console.log(jsx.queryStringToObject("a[fruits][red][]=strawberry"));
console.log(jsx.queryStringToObject("a[fruits][red][]=strawberry&a[1]=five&a[fruits][red][]=cherry&a[fruits][yellow][]=lemon&a[fruits][yellow][688]=banana"));

这将输出如下内容:

{ a: '1' }
{ a: '3' }
{ a: { '0': '1' } }
{ a: { '0': '1', '1': 'pomme' } }
{ a: { '0': 'one', '1': 'five' } }
{ foo: 'bar', number: '1234' }
{
  a: { fruits: { red: { '0': 'strawberry' } } }
}
{
  a: {
    '1': 'five',
    fruits: {
      red: { '0': 'strawberry', '1': 'cherry' },
      yellow: { '0': 'lemon', '688': 'banana' }
    }
  }
}

注意:它基于locutus parse_str函数(https://locutus.io/php/strings/parse_str/)。

答案 21 :(得分:1)

console.log(decodeURI('abc=foo&def=%5Basf%5D&xyz=5')
  .split('&')
  .reduce((result, current) => {
    const [key, value] = current.split('=');

    result[key] = value;

    return result
  }, {}))

答案 22 :(得分:1)

ES6 有一个非常简单且不正确的答案:

console.log(
  Object.fromEntries(new URLSearchParams(`abc=foo&def=%5Basf%5D&xyz=5`))
);

但是这一行代码没有覆盖多个相同的键,你必须使用更复杂的东西:

function parseParams(params) {
  const output = [];
  const searchParams = new URLSearchParams(params);

  // Set will return only unique keys()
  new Set([...searchParams.keys()])
    .forEach(key => {
      output[key] = searchParams.getAll(key).length > 1 ?  
        searchParams.getAll(key) : // get multiple values
        searchParams.get(key); // get single value
    });

  return output;
}

console.log(
   parseParams('abc=foo&cars=Ford&cars=BMW&cars=Skoda&cars=Mercedes')
)

代码将生成如下结构:

[
  abc: "foo"
  cars: ["Ford", "BMW", "Skoda", "Mercedes"]
]

答案 23 :(得分:1)

2019一线方法

针对您的具体情况:

Object.fromEntries(new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5'));

对于更常见的情况,有人想要将查询参数解析为对象:

Object.fromEntries(new URLSearchParams(location.search));

如果您无法使用Object.fromEntries,这也将起作用:

Array.from(new URLSearchParams(window.location.search)).reduce((o, i) => ({ ...o, [i[0]]: i[1] }), {});

答案 24 :(得分:1)

对于Node,您可以使用以下内容:

const querystring = require('querystring');

querystring.parse('abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar');
// returns the object

文档:https://nodejs.org/api/querystring.html

答案 25 :(得分:1)

如果您使用的是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
};

答案 26 :(得分:1)

{{1}}

答案 27 :(得分:1)

这是我的快速和肮脏的版本,基本上它拆分了由&#39;&amp;&#39;分隔的网址参数。到数组元素,然后迭代该数组添加由&#39; =&#39;分隔的键/值对成对象。我使用decodeURIComponent()将编码字符转换为正常的字符串等价物(因此%20变为空格,%26变为&#39;&amp;&#39;等):

function deparam(paramStr) {
    let paramArr = paramStr.split('&');     
    let paramObj = {};
    paramArr.forEach(e=>{
        let param = e.split('=');
        paramObj[param[0]] = decodeURIComponent(param[1]);
    });
    return paramObj;
}

示例:

deparam('abc=foo&def=%5Basf%5D&xyz=5')

返回

{
    abc: "foo"
    def:"[asf]"
    xyz :"5"
}

唯一的问题是xyz是一个字符串而不是一个数字(由于使用了decodeURIComponent()),但除此之外它不是一个糟糕的起点。

答案 28 :(得分:1)

我在这里使用的是:

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);

基本用法,例如 ?a=aa&b=bb
Object {a: "aa", b: "bb"}

重复参数,例如 ?a=aa&b=bb&c=cc&c=potato
Object {a: "aa", b: "bb", c: ["cc","potato"]}

缺少钥匙,例如 ?a=aa&b=bb&=cc
Object {a: "aa", b: "bb"}

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

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

答案 29 :(得分:0)

我以这种方式这样做:

const uri = new URL('https://example.org/?myvar1=longValue&myvar2=value')
const result = {}
for (let p of uri.searchParams) {
  result[p[0]] = p[1]
}

答案 30 :(得分:0)

Mike Causer's answer之上构建我已经创建了这个函数,它考虑了具有相同键(foo=bar&foo=baz)和逗号分隔参数(foo=bar,baz,bin)的多个参数。它还允许您搜索某个查询键。

function getQueryParams(queryKey) {
    var queryString = window.location.search;
    var query = {};
    var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        var key = decodeURIComponent(pair[0]);
        var value = decodeURIComponent(pair[1] || '');
        // Se possui uma vírgula no valor, converter em um array
        value = (value.indexOf(',') === -1 ? value : value.split(','));

        // Se a key já existe, tratar ela como um array
        if (query[key]) {
            if (query[key].constructor === Array) {
                // Array.concat() faz merge se o valor inserido for um array
                query[key] = query[key].concat(value);
            } else {
                // Se não for um array, criar um array contendo o valor anterior e o novo valor
                query[key] = [query[key], value];
            }
        } else {
            query[key] = value;
        }
    }

    if (typeof queryKey === 'undefined') {
        return query;
    } else {
        return query[queryKey];
    }
}

示例输入: foo.html?foo=bar&foo=baz&foo=bez,boz,buz&bar=1,2,3

示例输出

{
    foo: ["bar","baz","bez","boz","buz"],
    bar: ["1","2","3"]
}

答案 31 :(得分:0)

首先需要定义什么是获取VAR:

function getVar()
{
    this.length = 0;
    this.keys = [];
    this.push = function(key, value)
    {
        if(key=="") key = this.length++;
        this[key] = value;
        this.keys.push(key);
        return this[key];
    }
}

不仅仅是阅读:

function urlElement()
{
    var thisPrototype = window.location;
    for(var prototypeI in thisPrototype) this[prototypeI] = thisPrototype[prototypeI];
    this.Variables = new getVar();
    if(!this.search) return this;
    var variables = this.search.replace(/\?/g,'').split('&');
    for(var varI=0; varI<variables.length; varI++)
    {
        var nameval = variables[varI].split('=');
        var name = nameval[0].replace(/\]/g,'').split('[');
        var pVariable = this.Variables;
        for(var nameI=0;nameI<name.length;nameI++)
        {
            if(name.length-1==nameI) pVariable.push(name[nameI],nameval[1]);
            else var pVariable = (typeof pVariable[name[nameI]] != 'object')? pVariable.push(name[nameI],new getVar()) : pVariable[name[nameI]];
        }
    }
}

并使用如:

var mlocation = new urlElement();
mlocation = mlocation.Variables;
for(var key=0;key<mlocation.keys.length;key++)
{
    console.log(key);
    console.log(mlocation[mlocation.keys[key]];
}

答案 32 :(得分:0)

我还需要在网址(decodeURIComponent doesn't)的查询部分处理+,因此我改编了沃尔夫冈的代码:

var search = location.search.substring(1);
search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)}):{};

就我而言,我使用jQuery来获取支持URL的表单参数,然后使用这个技巧来构建一个对象,然后我就可以轻松更新对象上的参数并重建查询URL,例如:

var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)});
objForm.anyParam += stringToAddToTheParam;
var serializedForm = $.param(objForm);

答案 33 :(得分:0)

这是一个更精简的 silicakes' approach 版本。

以下函数可以从 USVStringLocation 解析查询字符串。

/**
 * Returns a plain object representation of a URLSearchParams object.
 * @param {USVString} search - A URL querystring
 * @return {Object} a key-value pair object from a URL querystring
 */
const parseSearch = (search) =>
  [...new URLSearchParams(search).entries()]
    .reduce((acc, [key, val]) => ({
      ...acc,
      // eslint-disable-next-line no-nested-ternary
      [key]: Object.prototype.hasOwnProperty.call(acc, key)
        ? Array.isArray(acc[key])
          ? [...acc[key], val]
          : [acc[key], val]
        : val
    }), {});

/**
 * Returns a plain object representation of a URLSearchParams object.
 * @param {Location} location - Either a document or window location, or React useLocation()
 * @return {Object} a key-value pair object from a URL querystring
 */
const parseLocationSearch = (location) => parseSearch(location.search);

console.log(parseSearch('?foo=bar&x=y&ids=%5B1%2C2%2C3%5D&ids=%5B4%2C5%2C6%5D'));
.as-console-wrapper { top: 0; max-height: 100% !important; }

这是上面代码的一行代码(125 字节):

<块引用>

其中 fparseSearch

f=s=>[...new URLSearchParams(s).entries()].reduce((a,[k,v])=>({...a,[k]:a[k]?Array.isArray(a[k])?[...a[k],v]:[a[k],v]:v}),{})

编辑

这是一种序列化和更新的方法:

const parseSearch = (search) =>
  [...new URLSearchParams(search).entries()]
    .reduce((acc, [key, val]) => ({
      ...acc,
      // eslint-disable-next-line no-nested-ternary
      [key]: Object.prototype.hasOwnProperty.call(acc, key)
        ? Array.isArray(acc[key])
          ? [...acc[key], val]
          : [acc[key], val]
        : val
    }), {});

const toQueryString = (params) =>
  `?${Object.entries(params)
    .flatMap(([key, values]) =>
      Array.isArray(values)
        ? values.map(value => [key, value])
        : [[key, values]])
    .map(pair => pair.map(val => encodeURIComponent(val)).join('='))
    .join('&')}`;

const updateQueryString = (search, update) =>
  (parsed =>
    toQueryString(update instanceof Function
      ? update(parsed)
      : { ...parsed, ...update }))
  (parseSearch(search));

const queryString = '?foo=bar&x=y&ids=%5B1%2C2%2C3%5D&ids=%5B4%2C5%2C6%5D';
const parsedQuery = parseSearch(queryString);
console.log(parsedQuery);
console.log(toQueryString(parsedQuery) === queryString);

const updatedQuerySimple = updateQueryString(queryString, {
  foo: 'baz',
  x: 'z',
});
console.log(updatedQuerySimple);
console.log(parseSearch(updatedQuerySimple));

const updatedQuery = updateQueryString(updatedQuerySimple, parsed => ({
  ...parsed,
  ids: [
    ...parsed.ids,
    JSON.stringify([7,8,9])
  ]
}));
console.log(updatedQuery);
console.log(parseSearch(updatedQuery));
.as-console-wrapper { top: 0; max-height: 100% !important; }

答案 34 :(得分:-1)

许多其他解决方案没有考虑边缘情况。

这个手柄

  • 空键 a=1&b=2&
  • 空值 a=1&b
  • 空值 a=1&b=
  • 未编码的等号 a=1&b=2=3=4
  decodeQueryString: qs => {
    // expects qs to not have a ?
    // return if empty qs
    if (qs === '') return {};
    return qs.split('&').reduce((acc, pair) => {
      // skip no param at all a=1&b=2&
      if (pair.length === 0) return acc;
      const parts = pair.split('=');
      // fix params without value
      if (parts.length === 1) parts[1] = '';
      // for value handle multiple unencoded = signs
      const key = decodeURIComponent(parts[0]);
      const value = decodeURIComponent(parts.slice(1).join('='));
      acc[key] = value;
      return acc;
    }, {});
  },