Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
user2077469 Avatar asked Jun 11 '26 14:06

user2077469


1 Answers

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.

like image 153
Niet the Dark Absol Avatar answered Jun 16 '26 18:06

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!