Giovane
Giovane

Reputation: 41

javascript counting vowels, consonants and show the occurrance

I'm having trouble to figure out how to count vowels, consonants and declare how often the vowels appears separately, from user input. The user put any text ex: “Mischief managed!” and result must be: a: 2 e: 2 i: 2 o: 0 u: 0 non-vowels: 11

var userData = prompt ("Enter any text here");
var a = 0;
var e = 0;
var i = 0;
var o = 0;
var u = 0;
var consonants = 0;
var count;

for (count = 0; count <= userData.legth; count++){
   if((userData.charAt(count).match(/[aeiou]/))){       
     a++;
     e++;
     i++;
     o++;
     u++;
    }else if((userData.charAt(count).match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/))){

    consonants++;
}
}
 console.log ("a: " + a);
 console.log ("e: " + e);
 console.log ("i: " + i);
 console.log ("o: " + o);
 console.log ("u: " + u);
 console.log ("consonants: " + consonants);

But it's not working. I already searched in many other forums but, I didn't find anything like this.

Upvotes: 3

Views: 10357

Answers (8)

Rishu Ranjan
Rishu Ranjan

Reputation: 574

We can use regular expression to match vowels in a string.

Regular expression to match all occurrence of vowel in a string:/[aeiouAEIOU]+?/g

Below is the working code snippet:

    //function that takes string as input
    //function returns an object containing vowel count without case in account.
    function vowelCount(input) {
        //to get vowel count using string.match
        var arrVowels =input.match(/[aeiouAEIOU]+?/g);

        //acc=accumulator, curr=current value
        var countVowCons= arrVowels.reduce(function (acc, curr) {
           if (typeof acc[curr.toLowerCase()] == 'undefined') {
               acc[curr.toLowerCase()] = 1;
           } 
           else {
               acc[curr.toLowerCase()] += 1;
           }
           return acc;
           // the blank object below is default value of the acc (accumulator)
           }, {}); 

        countVowCons.NonVowels= input.match(/[^aeiouAEIOU]+?/g).length;
        return countVowCons;        
      }

Upvotes: 1

Redu
Redu

Reputation: 26201

Well for the sake of better coding and performance i would do this like this;

var str = "the quick brown fOx jUmps OvEr the lazy dog";

function getVowelCount(s) {
  var lut = {
      a: "0",
      e: "0",
      i: "0",
      o: "0",
      u: "0"
    },
    a = s.split("").map(c => c.toLowerCase());
  return a.reduce((p, c) => (p[c] && 1 * p[c]++, p), lut);
}
console.log(getVowelCount(str));

Upvotes: 1

tjchecketts
tjchecketts

Reputation: 110

This is another way to do it, but the general idea of splitting the text, looping through each letter and counting the vowels is similar to what others are posting about as well.

getCount = (str) => {
  var vowelsCount = 0;
  str = str.split('');
    for(var i = 0; i<str.length; i++) {
      if(str[i] === "a" || str[i] === "e" || str[i] === "i" || str[i] === "o" || str[i] === "u"){
        vowelsCount++;
    }
  }
  return vowelsCount;
}

console.log(getCount('onomatopoeia'));

Upvotes: 0

Alex Kudryashev
Alex Kudryashev

Reputation: 9480

First count all letters and then filter what you need.

function cntLetters(inp){
  var result={};
  var vowels = 'aeiouy'.split('');
  var inpArr=inp.split('');
  for(var i=0,n=inpArr.length;i<n;i++){
    result[inpArr[i]] = (result[inpArr[i]]||0)+1;
    if(vowels.indexOf(inpArr[i]) > -1)
       result['vowels'] = (result['vowels'] || 0) + 1;
  }
  return result;
}
var cnt = cntLetters('see your later');
console.log(cnt['a']);
console.log(cnt['e']);

If you want case-insensitive use var inpArr=inp.toLowerCase().split('');

Upvotes: 0

d1820
d1820

Reputation: 188

I would do something like this

var alpha = function(){      
  this.a = 0;
  this.e = 0;
  this.i = 0;
  this.o = 0;
  this.u = 0;
  this.other = 0;    
}

function counter(word, alpha) {
  for (i = 0; i < word.length; i++) {
    var chr = word.charAt(i).toLowerCase();
    if (alpha.hasOwnProperty(chr)) {
      alpha[chr]++;
    } else {
      alpha.other++;
    }
  }
}

function checkWord()
{
  var a = new alpha();
  counter("test", a); 
  console.log(a);         
}

In action can be seen in Plunker

Upvotes: 0

Firstly, let's point out some things

for (count = 0; count <= userData.legth; count++){

Length is missing letter 'n' and you don't need count to be less than or equal because you already start from index 0. So you just need less than.

Also:

if((userData.charAt(count).match(/[aeiou]/))){       
    a++;
    e++;
    i++;
    o++;
    u++;
} else if((userData.charAt(count).match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/))){
    consonants++;
}

What you are doing here is that every time it matches a vowel, you increment the variable for all of them, so for the word hi it would print that every vowel had one count. So take a look at this one:

var userData = prompt("Enter any text here").toLowerCase();
var a = 0;
var e = 0;
var i = 0;
var o = 0;
var u = 0;
var consonants = 0;
var count;

for (count = 0; count < userData.length; count++){
    var char = userData.charAt(count);
    if(char.match(/[aeiou]/)){
        switch (char) {
            case 'a':
                a++;
                break;
            case 'e':
                e++;
                break;
            case 'i':
                i++;
                break;
            case 'o':
                o++;
                break;
            case 'u':
                u++;
                break;
        }
    } else if(char.match(/[bcdfghjklmnpqrstvwxyz]/)) {
        consonants++;
    }
}

console.log ("a: " + a);
console.log ("e: " + e);
console.log ("i: " + i);
console.log ("o: " + o);
console.log ("u: " + u);
console.log ("consonants: " + consonants);

I am following your logic to keep it simple and better readable for you. We match the regular expression the same way you do, but we also check what is the exact character right now, so we can increment the correct variable.

For the else if, in order to minimize a bit your regular expression we just check if it matches one of the lower case letters, because we convert the userData to lower case, as soon as we get it:

var userData = prompt("Enter any text here").toLowerCase();

Try my example and see if it fits your needs.

Upvotes: 3

1983
1983

Reputation: 5973

Well, you need to check which vowel you're encountering and then update the appropriate variable.

But for is rarely needed. JavaScript provides higher-level array iteration functions which among other things, will prevent mistakes such as off-by-one errors, like you have in your code :-)

And though your input is a string, not an array, you can turn it into one by using String.prototype.split.

var input = 'Mischief managed!';

var result = input.split('').reduce(function(result, c){
    c = c.toLowerCase();
    if(c in result){
        result[c] += 1;
    }else{
        result.other += 1;
    }
    return result;
}, {a:0, e:0, i:0, o:0, u:0, other:0});

console.log(JSON.stringify(result));

I've used Array.prototype.reduce here, but you may, initially, find Array.prototype.forEach easier to get your head around.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386883

You could use

var userData = prompt("Enter any text here"),
    count = userData.split('').reduce(function (r, a) {
        var vowels = ['a', 'e', 'i', 'o', 'u'],
        p = vowels.indexOf(a.toLowerCase());
    if (~p) {
        r[vowels[p]] = (r[vowels[p]] || 0) + 1;
    } else {
        r['non-vowels']= (r['non-vowels']|| 0) + 1;
    }
    return r;
}, Object.create(null));

console.log(count);

Upvotes: 0

Related Questions