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,870
  • 7
  • 28
  • 46

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
  • 85,780
  • 21
  • 159
  • 179
1
var p = /(aaa)/g;
var t = "someaaa textaaa toaaa testaaa aaagainst";
t.match(p);
slomek
  • 4,873
  • 3
  • 17
  • 16