ousecTic
ousecTic

Reputation: 1925

Do not understand vowel count code for javascript?

function getCount(str) {
  return (str.match(/[aeiou]/ig)||[]).length;
}

This code at code-war counts the amount of vowel in a string.It works perfectly fine; but, I trying to understand how it works.

Upvotes: 0

Views: 1027

Answers (1)

VLAZ
VLAZ

Reputation: 29116

/[aeiou]/ig is a regular expression that will match any vowel. It will match any of a, e, i, o, u, the i flag (/[aeiou]/ig) makes it case-insensitive and the g flag stands for "global" or in other words "don't stop after the first match".

The String#match method takes a regular expression and returns any matches. So with the above regular expression, you would pass a word and return an array of all the vowels in it. For example

var resultOfStringMatch = "The quick brown fox jumps over the lazy dog".match(/[aeiou]/ig);

console.log(resultOfStringMatch)

There is a special case - if the initial string does not have any vowels, then the output would be the value null.

var resultOfStringMatch = "Th qck brwn fx jmps vr th lzy dg".match(/[aeiou]/ig);

console.log(resultOfStringMatch)

For that purpose the ||[] is used which will return an empty array if the preceding value is falsey.

console.log(true || "some string");
console.log(false || "some string");

console.log(null || "null is a falsey value");

So, at the end the expression str.match(/[aeiou]/ig)||[] will always return an array. If you check its length property, you would find the number of vowels.

Upvotes: 1

Related Questions