Regex to grab strings between square brackets

前端 未结 6 555
[愿得一人]
[愿得一人] 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:41

    You are almost there, you just need a global match (note the /g flag):

    match(/\[(.*?)\]/g);
    

    Example: http://jsfiddle.net/kobi/Rbdj4/

    If you want something that only captures the group (from MDN):

    var s = "pass[1][2011-08-21][total_passes]";
    var matches = [];
    
    var pattern = /\[(.*?)\]/g;
    var match;
    while ((match = pattern.exec(s)) != null)
    {
      matches.push(match[1]);
    }
    

    Example: http://jsfiddle.net/kobi/6a7XN/

    Another option (which I usually prefer), is abusing the replace callback:

    var matches = [];
    s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
    

    Example: http://jsfiddle.net/kobi/6CEzP/

提交回复
热议问题