[removed] How to get multiple matches in RegEx .exec results

后端 未结 6 1597
遥遥无期
遥遥无期 2020-12-09 02:54

When I run

/(a)/g.exec(\'a a a \').length

I get

2

but I thought it should return

3
         


        
6条回答
  •  佛祖请我去吃肉
    2020-12-09 03:00

    exec() is returning only the set of captures for the first match, not the set of matches as you expect. So what you're really seeing is $0 (the entire match, "a") and $1 (the first capture)--i.e. an array of length 2. exec() meanwhile is designed so that you can call it again to get the captures for the next match. From MDN:

    If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property).

提交回复
热议问题