Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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

Problem courtesy of: Trindaz

Solution

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

Solution courtesy of: Andrew Cheong

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×