0
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.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
ousecTic
  • 1,895
  • 11
  • 20
  • it runs over the string that you send it and find all the 'aeiou' chars and return the amount of it(length of the array that you insert in to it. – Talg123 Oct 24 '18 at 17:52
  • What part exactly is the problem? The regular expression? The `||` operator? – Andreas Oct 24 '18 at 17:54
  • 1
    `str.match(/[aeiou]/ig)` returns an array with all the characters that match the regex, and `.length` returns the length of the array. – Nir Alfasi Oct 24 '18 at 17:54
  • This function uses [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) to match against the letters [aeiou]. The 'ig' is telling the match that to match with no regard to upper/lowercase (letter 'i'), and to list all matches globally (letter 'g'). – Dave Oct 24 '18 at 17:55
  • Got it thanks for the help – ousecTic Oct 24 '18 at 17:56

1 Answers1

1

/[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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67