16

It's my understanding that all three of these lines below should return an ARRAY with 2 results in it. Yet RegExp will only return 1 result no matter how many times the regex repeats in the string.

Can some one explain why? And perhaps suggest how I can get RegExp to give me global results?

//INTPUT: 
    console.log(new RegExp("New York", "gi").exec("New York New York")); 

//OUTPUT: 
["New York"]

//INTPUT: 
    console.log(new RegExp(/New York/gi).exec("New York New York"));

//OUTPUT: 
["New York"]

//INTPUT: 
    console.log("New York New York".match(/New York/gi));

//OUTPUT:
["New York", "New York"]
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
StefanHayden
  • 3,569
  • 1
  • 31
  • 38
  • now what really intrigues me is that if you try `(' New York New York ').match(/ New York /gi)` it will bring just 1 result (as kinda expected) and I can't think of a better way to go around this (when otherwise needed) [other than iterating over it](http://stackoverflow.com/questions/42328875/javascript-regex-to-remove-all-numbers-with-specific-lenght-or-do-a-persistent)! :( – cregox Feb 19 '17 at 15:11

2 Answers2

26

your third example is the best way to get the array of matches.

RegExp.exec actually remembers its position, and returns the next result on subsequent calls:

>>> var v = /new york/gi
>>> v.exec("NEW YORK new york")
["NEW YORK"]
>>> v.exec("NEW YORK new york")
["new york"]
>>> v.exec("NEW YORK new york")
null
Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
13

This is expected, exec() returns a single match but provides more info about the match than match(). If you just want all the matches, use match(). From JavaScript: The Definitive Guide:

Recall that match() returns an array of matches when passed a global regular expresion. exec(), by contrast, always returns a single match and provides complete information about that match. When exec() is called on a regular epression that has the g flag, it sets the lastIndex property of the matched substring. When exec() is invoked a second time for the same regular expression, it begins its search at the character position indicated by the lastIndex property.

Derek Swingley
  • 8,734
  • 5
  • 32
  • 33