user2077469
user2077469

Reputation: 1189

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?

Upvotes: 2

Views: 4595

Answers (6)

Deepeshkumar
Deepeshkumar

Reputation: 443

A different approach,

const vowels = (str) => [...str].filter((ch) => ["a", "e", "i", "o", "u"].includes(ch)).length;
console.log(vowels("aaaa"));

Upvotes: 0

Winnemucca
Winnemucca

Reputation: 3458

You can use the .match to compare a string to a regular expression. g is global which will run through the entire string. i makes the string readable as upper and lower case.

function getVowels(str) {
      var m = str.match(/[aeiou]/gi);
      return m === null ? 0 : m.length;
    }

Upvotes: 0

Dragos C
Dragos C

Reputation: 363

The simplest way is

s.match(/[aeiou]/gi).length

Upvotes: 1

Muhammad Hani
Muhammad Hani

Reputation: 8664

Regarding your code, your if condition needs no i2

if('aouie'.search(a[i]) > -1){ 

I wonder, why all that use of arrays and nested loops, the below regex could do it better,

var str = "run forest, run";
var matches = str.match(/[aeiou]/gi);
    var count = matches ? matches.length : 0;
    alert(count + " vowel(s)");

Demo

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

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.

Upvotes: 5

Paul
Paul

Reputation: 22005

Try:

a = "run forest, run";

var syl = 0;

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

alert(syl+" vowels")

First, the split is useless since you can already cycle through every character.

Second: you need to use i<a.length, this gets the last character in the string, too.

Upvotes: 2

Related Questions