Search code examples
javascriptmeteor

Javascript Regex match missing odd index


This Meteor client code which uses regex to match words in a sentence, it matches fine but only on index 0 and even number index. why is it not matching on every index number? Thanks

  let matches = '2006 BLUE TOYOTA COROLLA 120 SER SEDAN'.match(/[A-Z0-9]*/gi)
  console.log('yr: ', matches[0])       //2006
  console.log('color: ', matches[1])    // blank, why?
  console.log('color?: ', matches[2])   //BLUE
  console.log('make?: ', matches[3])    // blank, why?
  console.log('make: ', matches[4])     //TOYOTA
  console.log('modle: ', matches[6])    //COROLLA
})


Solution

  • it happens because you use * operator instead of + difference between them is:

    * - 0 or more of the preceding expression

    + - 1 or more of the preceding expression

    so in your case * operator takes this empty space as "0 or more" and thinks, that it is a separate element, expression, that you probably want is:

    let matches = '2006 BLUE TOYOTA COROLLA 120 SER SEDAN'.match(/[A-Z0-9]+/gi)