0

I'm having trouble accessing the full list of results when I .exec() a regular expression in Node. Here is my code:

var p = /(aaa)/g;
var t = "someaaa textaaa toaaa testaaa aaagainst";
p.exec(t);
> [ 'aaa', 'aaa', index: 4, input: 'someaaa textaaa toaaa testaaa aaagainst' ]

I only get two results, no matter what. Is my error on the RegExp itself?

Any help will be appreciated!

Jo Colina
  • 1,728
  • 6
  • 24
  • 39

2 Answers2

1

exec will only return the first matched result. To get all the results

  1. Use match

    var p = /(aaa)/g;
    var t = "someaaa textaaa toaaa testaaa aaagainst";
    var matches = t.match(p);
    

var p = /(aaa)/g,
  t = "someaaa textaaa toaaa testaaa aaagainst";
var matches = t.match(p);

console.log(matches);
  1. Use while with exec

    while(match = p.exec(t)) console.log(match);
    

var p = /(aaa)/g,
  t = "someaaa textaaa toaaa testaaa aaagainst";

var matches = [];
while (match = p.exec(t)) {
  matches.push(match[0]);
}

console.log(matches);

Read: match Vs exec in JavaScript

Community
  • 1
  • 1
Tushar
  • 82,599
  • 19
  • 151
  • 169
1
var p = /(aaa)/g;
var t = "someaaa textaaa toaaa testaaa aaagainst";
t.match(p);
slomek
  • 4,593
  • 3
  • 15
  • 16