【问题标题】:Parse url with arrays in javascript用javascript中的数组解析url
【发布时间】:2018-03-23 03:44:41
【问题描述】:

我从 GET 方法中输入了以下格式的 url

rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so

我正在尝试使用以下代码对其进行解析:

function getParameterByName(name){
                    var url = window.location.search;
                    name = name.replace(/[\[\]]/g, "\\$&");
                    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
                    results = regex.exec(url);
                    if (!results) return null;
                    if (!results[2]) return '';
                    return decodeURIComponent(results[2].replace(/\+/g, " "));
                }

但是当我将myInputs_1 传递给函数时,它返回null。

我以某种方式计划生成以下格式的输出:

myInput_1 = ['things', 'are', 'working']
myInput_2 = ['i', 'hope']
myInput_3 = ['so']

但我无法提取单个值。有没有办法达到预期的输出?

edit_1

我了解到%5B[%5D],但是即使我将myInput_1[] 作为参数传递给函数,它仍然返回null,我不知道为什么

【问题讨论】:

    标签: javascript html regex parsing


    【解决方案1】:

    您可以使用URL 实例的URLSearchParams 对象:

    s = "http://example.com/rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so"
    
    url = new URL(s)
    searchParams = url.searchParams
    
    console.log(searchParams.getAll("myInputs_1[]"))
    // ["things", "are", "working"]
    

    【讨论】:

    • 您的回答确实简洁,但我有浏览器兼容性要求。将来,如果可能的话,人们应该使用它。
    【解决方案2】:

    使用.execfind successive matches 时需要做一个while 循环。另外,我简化了你的正则表达式。

    function getParameterByName(name){
        var url = decodeURIComponent(window.location.search);
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "=([^&#]*)", 'g');
        var match, result = [];
        while ((match = regex.exec(url)) !== null)
            result.push(match[1]);
        return result;
    }
    

    除非您的浏览器兼容性对您很重要,否则我建议您选择 Jean 的答案。

    【讨论】:

      【解决方案3】:

      非正则表达式

      function getParamByName(name){
          var value = []
          paramsArray = decodeURIComponent(window.location.search).split("?")[1].split("&")
          paramsArray.forEach(function(d){
              if(d.indexOf(name) > -1){
                  value.push(d.split("=")[1])
              }
          })
          return value;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2011-10-02
        • 1970-01-01
        • 2011-04-25
        • 1970-01-01
        • 2022-01-03
        相关资源
        最近更新 更多