Reputation: 1924
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!
Upvotes: 0
Views: 81
Reputation: 87233
exec
will only return the first matched result. To get all the results
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);
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
Upvotes: 1
Reputation: 5136
var p = /(aaa)/g;
var t = "someaaa textaaa toaaa testaaa aaagainst";
t.match(p);
Upvotes: 1