Home > Blockchain >  How to return number of vowels in a string in Javascript?
How to return number of vowels in a string in Javascript?

Time:03-01

I would be delighted if someone could look into my code. I have been trying to return the total number of vowels in a given string. I want my code to take into account of cases of the letter, any empty spaces in the string and also absence of vowel. I believe there is something wrong with my if-statement which is returning 0 for the string input "Crypt" and "Crypto"

function countVowels(str) {

  let count = 0;
  let arr = str.toLowerCase().split("")
  let vowels = ["a","e","i","o","u"]
  console.log(arr)

  for (let i = 0; i < str.length; i  ){
    if (arr[i].includes(vowels)){
      count  
    } else {
      return 0
    }
  }
  return count 

}
console.log(countVowels("Crypto"))
console.log(countVowels("Crypt"))

CodePudding user response:

There are several problems with the code you've produced here.

The first is that, for each letter in the string, you're checking whether the letter includes the array of vowels, which will never be true. You've effectively written this...

"a".includes(["a", "e", "i", "o", "u"])

which is backwards.

Instead you need to ask the array whether it includes the given, letter, this way:

["a", "e", "i", "o", "u"].includes("a") // true
["a", "e", "i", "o", "u"].includes("s") // false

The second problem is that, in your else branch, you return 0. This will immediately halt your function and return 0 the first time you encounter a non-vowel. Instead of return 0, you can simply take no action, and drop the else branch entirely.

Ultimately your loop should look like this:

  for (let i = 0; i < str.length; i  ){
    if (vowels.includes(arr[i])) {
      count  
    }
  }

CodePudding user response:

function countVowels(str) {
  return str.split(/[aeiou]/).length - 1;
}

CodePudding user response:

there are a lo of solution to this.

i think you are just starting so i hope following will help

function countVowels(str) {

  let count = 0;
  let arr = str.toLowerCase().split("");
  

  for (let i = 0; i < str.length; i  ){
    if (arr[i] === "a" || arr[i] === "e" || arr[i] === "i" || arr[i] === "o" || arr[i] === "u")){
//same as count   but good practice
     count =1
    } else {
      return 0
    }
  }
  return count 

}
console.log(countVowels("Crypto"))
console.log(countVowels("Crypt"))

CodePudding user response:

In your for loop, the expression:

arr[i].includes(vowels)
// It should be...
vowels.includes(arr[i])

.includes() is a String and an Array method so it can be confusing to a novice. In general, you want to prefix the method with array or string that serves as the filter (the string/array used to compare with the input value).

Also, the else statement will short-circut your function because return ends the whole function immediately. The if statement is sufficient, if there isn't a match then the for loop will just ignore it.

function countVowels(str) {
  let count = 0;
  let arr = str.toLowerCase().split("");
  let vowels = ["a", "e", "i", "o", "u"];
  for (let i = 0; i < str.length; i  ) {
    if (vowels.includes(arr[i])) {
      count  
    }
  }
  return count;
}
console.log(countVowels("Crypto"))
console.log(countVowels("Crypt"))

As a more efficient alternative use .filter() like so and return V.length:

const V = array.filter(char => vowels.includes(char));

function countVowels(str) {
  let array = str.toLowerCase().split("");
  const vowels = ["a", "e", "i", "o", "u"];
  const V = array.filter(char => vowels.includes(char));
  return V.length;
};

console.log(countVowels("Crypto"))
console.log(countVowels("Crypt"))

CodePudding user response:

Language is complicated. There are more vowel characters in English than are contained in the string ['a', 'e', 'i', 'o', 'u'], mainly because of accents that show up in borrowed words such as "Café".

So before you try to detect vowels in a string, you may want to decompose it using String.prototype.normalize with the 'NFD' flag to decompose accented characters into their base and a control character.

For an unaccented string, such as 'Testing', the result should be identical to the input. But for an accented string, such as 'Café', the result will decompose any accented characters into their base character and a control character:

console.log(('Café').normalize('NFD').split(''));

Once you've done this decomposition, then you can use your list of unmodified vowels. I'd recommend using String.prototype.split to convert the string into an array, and then Array.prototype.filter to remove all non-vowel characters from the array so you can read its length:

function getNumVowels(str) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];

  const decomposedStr = str.toLowerCase().normalize('NFD');
  const strArray = decomposedStr.split('');
  
  const vowelArr = strArray.filter((char) => vowels.includes(char));
  
  return vowelArr.length;
}

console.log(getNumVowels('Testing')); // <- 2
console.log(getNumVowels('Café')); // <- 2
console.log(getNumVowels('thfds ')); // <- 0

  • Related