JavaScript RegExp exec () method returns only one element

Possible duplicate:
Regex exec returns only the first match

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

returns "axbxdxd" as expected.

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

however, it returns an array containing one element: ["1"]. Shouldn't all matches be returned?

Thanks in advance!

+4
source share
1 answer

Not. You have to call exec several times:

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

Change The "Mozilla Developers Network" page on exec has much more to say about this feature. This is where I got the example and modified it for your question.

Change 2 . I modified the code above so that it is not an infinite loop. :-)

+5
source

Source: https://habr.com/ru/post/1395652/


All Articles