3

Possible Duplicate:
Regex exec only returning first match

"a1b2c3d".replace(/[0-9]/g,"x")

returns "axbxdxd" as expected.

/[0-9]/g.exec("a1b2c3d")

however only returns an array containing one item: ["1"]. Shouldn't it return all matches?

Thanks in advance!

Community
  • 1
  • 1
muffel
  • 7,004
  • 8
  • 57
  • 98

1 Answers1

5

No. You need to call exec multiple times:

var re = /[0-9]/g;
var input = "a1b2c3d";
var myArray;
while ((myArray = re.exec(input)) != null)
{
  var msg = "Found " + myArray[0] + ".  ";
  print(msg);
}

Edit: The Mozilla Developer Network page on exec has much more to say about this function. That's where I got the example and modified it for your question.

Edit 2: I've changed the above code so it isn't actually an infinite loop. :-)

CanSpice
  • 34,814
  • 10
  • 72
  • 86
  • unfortunately the example posted by you doesn't work - its an infinite loop returning only "1". Any idea? – muffel Feb 09 '12 at 18:42
  • 1
    @muffel: Try moving the regex to its own variable? `var re = /[0-9]/g;`...and then use that in the `while` loop: `while ((myArray = re.exec("a1b2c3d")) != null)` ? – CanSpice Feb 09 '12 at 18:44
  • 1
    Well, that was neat. Running the posted code in Chrome generated an infinite loop of print page windows. Had to kill it and come back. :-) BTW, yes, put it in a variable first. Otherwise you're recreating a fresh regex each iteration. – Wiseguy Feb 09 '12 at 18:47
  • I needed to move as well the regex as the string (?) to their own variables. Finally it works. Thank you! – muffel Feb 09 '12 at 18:52
  • @Wiseguy: fixed and fixed. :-) – CanSpice Feb 09 '12 at 19:25