James James - 1 year ago 70
Javascript Question

Regular expression not progressing after first match

The following code was my attempt to write a Regular Expression that would match both "cat" and "car" strings.

(function (){

console.log(/(ca(t|r))+?/.exec(["cat", "car", "catcoon"]));

The "ca" would be matched first, then the method would look for either a "t" or a "r". It is then wrapped with ()+? to allow for multiple matches.
However, the console shows
["cat", "cat", "t"]
indicating that is stuck after the first match.

Answer Source

exec syntax is:



str The string against which to match the regular expression.


Your not passing in a string, your passing in an array. JavaScript will corece this into a string as best it can. Basically you need:

(function (){
   for (var str in ["cat", "car", "catcoon"]){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download