Regex to grab strings between square brackets

前端 未结 6 548
[愿得一人]
[愿得一人] 2020-12-03 11:11

I have the following string: pass[1][2011-08-21][total_passes]

How would I extract the items between the square brackets into an array? I tried

6条回答
  •  攒了一身酷
    2020-12-03 11:38

    I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:

    var string = "pass[1][2011-08-21][total_passes]";
    var regex = /\[([^\]]*)\]/g;
    
    while (match = regex.exec(string)) {
       alert(match[1]);
    }
    

    Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.

提交回复
热议问题