2

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.

2
  • 4
    You need to loop over the results. exec only returns one match per call. Read the documentation on it.
    – trincot
    Oct 21, 2016 at 9:29
  • What you need of ah answer?
    – prasanth
    Oct 21, 2016 at 9:29

2 Answers 2

2

exec syntax is:

regexObj.exec(str)

Parameters

str The string against which to match the regular expression.

MDN

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 (){
   var arr = ["cat", "car", "catcoon"];
   for (var i = 0; i < arr.length; i++) {
     var str = arr[i];
     console.log(/(ca(t|r))+?/.exec(str));
   }
})()
0
0

Hope this help!

var result =["cat", "car", "catcoon", "cat", "car", "catcoon"].filter(x => /^ca[tr]$/.exec(x));

console.log(result)

Not the answer you're looking for? Browse other questions tagged or ask your own question.