Search code examples
javascriptstring

Counting vowels in javascript


I use this code to search and count vowels in the string,

a = "run forest, run";
a = a.split(" ");
var syl = 0;
for (var i = 0; i < a.length - 1; i++) {
    for (var i2 = 0; i2 < a[i].length - 1; i2++) {
        if ('aouie'.search(a[i][i2]) > -1) {
            syl++;
        }
    }
}

alert(syl + " vowels")

Obviously it should alert up 4 vowels, but it returns 3. What's wrong and how you can simplify it?


Solution

  • Try this:

    var syl = ("|"+a+"|").split(/[aeiou]/i).length-1;
    

    The | ensures there are no edge cases, such as having a vowel at the start or end of the string.