Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to get multiple matches in RegEx .exec results

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

like image 836
Trindaz Avatar asked Jun 29 '12 23:06

Trindaz


People also ask

What is the difference between exec () and test () methods in JavaScript?

Difference between test () and exec () methods in JavascriptTest tests for matches and returns booleans while exec captures groups and matches the regex to the input. If you only need to test an input string to match a regular expression, RegExp. test is most appropriate.

What does regex exec return?

JavaScript RegExp exec() The exec() method tests for a match in a string. If it finds a match, it returns a result array, otherwise it returns null.

Does regex match return array?

match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

What is exec () in JS?

The exec() Method in JavaScript is used to test for match in a string. If there is a match this method returns the first match else it returns NULL. Syntax: RegExpObject.exec(str) Where str is the string to be searched.


1 Answers

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).

like image 79
slackwing Avatar answered Sep 20 '22 08:09

slackwing