2017-10-11 82 views
4

阵列我从GET方法输入网址的格式如下解析URL在JavaScript中

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,我不知道为什么

回答

1

当使用.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; 
} 

我建议你去与吉恩的答案,除非你浏览器兼容性问题给你。

2

你可以使用一个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"] 
+0

您的回答非常简洁,但我有浏览器兼容性要求。在未来,如果可能的话,人们应该使用它。 – Adorn

0

非正则表达式的方式

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