When I run
/(a)/g.exec('a a a ').length
I get
2
but I thought it should return
3
because there are 3 as in the string, not 2!
Why is that?
I want to be able to search for all occurances of a string in RegEx and iterate over them.
FWIW: I’m using node.js
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: