Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why doesn't my global tag seem to work in this regular expression?

var myRegExp = /d/g;
var myString = "dogs and more dogs";
myRegExp.exec(myString);

Because the global "g" tag is included, I expected this to return an array with three "d"s. (Similar to what would happen with myString.match(myRegExp);) Instead I only get one. How come?

3 Answers

Hi Ryan,

The exec method doesn't work in the way that most people typically expect when using the g flag, what it allows you to do is iterate over each result through a while loop whereas match searches for everything at once and returns an array. See the below link which explains in more detail about successive matches using exec.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Example.3A_Finding_successive_matches

Thanks Chris!

Just extra info....

I learned in the process of really trying to understand this you can set a regular expression's lastIndex property, and using the regular expression's exec method, you can get the first match of a string from a particular index. e.g.

var myRegExp = /\w+/g;
myRegExp.lastIndex = 3;
var stringToBeChecked = "apples and oranges";
myRegExp.exec(stringToBeChecked);
// returns ["les"]

This only works with the global "g" flag; otherwise the lastIndex property is ignored and "apples" is returned.

Important: lastIndex changes each time the regular expression is used