Reputation: 343
I'm using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes()
help at all considering it is a string? I would like to use something like string.includes("a", "e", "i", "o", "u")
if at all possible to clean up the conditional statement. Also, is it needed to convert the input into a string?
function getVowels(str) {
var vowelsCount = 0;
//turn the input into a string
var string = str.toString();
//loop through the string
for (var i = 0; i <= string.length - 1; i++) {
//if a vowel, add to vowel count
if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
vowelsCount += 1;
}
}
return vowelsCount;
}
Upvotes: 11
Views: 127641
Reputation: 41
A simple solution that everyone might easily understand:
function getVowelCount(str){
var vowels = ["a","e","i","o","u"];
var count = 0;
var letter;
for(letter of str){
if(vowels.includes(letter)){
console.log(letter);
count++;
}
}
return count;
}
console.log(getVowelCount("John Doe"));
Upvotes: 0
Reputation: 111
function vowels(str) {
let count=0;
const checker=['a','e','i','o','u'];
for (let char of str.toLowerCase){
if (checker.includes(char)) {
count++;
}
return count;
}
function vowels(str) {
const match = str.match(/[aeiou]/gi);
return match ? match.length : 0 ;
}
Upvotes: 3
Reputation: 60
function vowelsCount(sentence) {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
let count = 0;
let letters = Array.from(sentence);
letters.forEach(function (value) {
if (vowels.includes(value)) {
count++
}
})
return count;
}
console.log(vowelsCount("StackOverFlow"));
Upvotes: 0
Reputation: 1
function vowelCount(str){
str=str.toLowerCase()
let count=[]
for(let i=0;i<str.length;i++){
if(str.charAt(i)=='u'||str.charAt(i)=='o'||str.charAt(i)=='i'||str.charAt(i)=='e'||str.charAt(i)=='a'){
count.push(str.charAt(i))//to store all the vowels in an array
}
}
let eachcount={}
count.forEach((x)=>eachcount[x]?eachcount[x]++:eachcount[x]=1) //to count each vowel from the count array
return eachcount
}
console.log(vowelCount("hello how Are You"))
Upvotes: 0
Reputation: 1424
Use match
but be careful as it can return a null if no match is found. This solves it:
const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);
Upvotes: 3
Reputation: 9268
Another solution using Set
to lookup characters in constant time and reduce()
to do the actual counting. The implementation also uses the spread syntax for string
as strings are Iterable
.
/**
* Count vowels in a string. Ignores case.
* @param {string} str String to count the vowels in
* @returns numbers of vowels
*/
function countVowels(str) {
let vowels = new Set("aeiou")
return [...str.toLowerCase()].reduce((count, character) => count + vowels.has(character) || 0, 0)
};
console.log(countVowels("apple"))
console.log(countVowels("pears are yummy"))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: -1
Reputation: 21
You can easily solve this using simple regex. match() method matches string agains a regex variable. return an array if the is a matches and return null if no match is found.
function getVowels(str) {
let vowelsCount = 0;
const regex = /[aiueo]/gi;
vowelsCount = str.match(regex);
return vowelsCount ? vowelsCount.length : 0;
}
console.log(getVowels('Hello World')) => return 3
console.log(getVoewls('bbbcccddd') => return 0
Upvotes: 2
Reputation: 11
After research and without using regex, this is what I found the simplest to understand for new devs like me.
function vowelCount (string) {
let vowel = "aeiouy"; // can also be array
let result = 0;
for (let i = 0; i < string.length; i++) {
if (vowel.includes(string[i].toLowerCase())) {
result++;
}
}
return result;
}
console.log(vowelCount("cAkeYE"));
Upvotes: 1
Reputation: 565
Here is the my solution for the problem:
function getVowelsCount(s) {
let vowels = ["a", "e", "i", "o", "u"];
let count=0;
for(let v of s) {
if(vowels.includes(v)){
console.log(v);
count=count+1;
}
}
console.log(count);
}
Upvotes: 1
Reputation: 21
My solution:
const str = "In West Philadephia, born and raised.";
const words = str.split("");
function getVowelCount() {
return words.filter(word => word.match(/[aeiou]/gi)).length;
}
console.log(getVowelCount());
Output: 12
Upvotes: 2
Reputation: 41
One more method (using reduce
):
function getVowels(str) {
return Array.from(str).reduce((count, letter) => count + 'aeiou'.includes(letter), 0);
}
Upvotes: 1
Reputation: 81
You can use the simple includes function, which returns true if the given array contains the given character, and false if not.
Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.
for (var i = 0; i <= string.length - 1; i++) {
if ('aeiou'.includes(string[i].toLowerCase())) {
vowelsCount += 1;
}
}
Upvotes: 4
Reputation: 5577
The following works and is short:
function countVowels(str) {
return ( str = str.match(/[aeiou]/gi)) ? str.length : 0;
}
console.log(countVowels("abracadabra")); // 5
console.log(countVowels("")); // 0
Upvotes: 1
Reputation: 41
Use this function to get the count of vowels within a string. Works pretty well.
function getVowelsCount(str)
{
//splits the vowels string into an array => ['a','e','i','o','u','A'...]
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
/*for each of the elements of the splitted string(i.e. str), the vowels list would check
for any occurence and increments the count, if present*/
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
//and now log this count
console.log(count);}
//Function Call
getVowelsCount("World Of Programming");
Output for the given string would be 5. Try this out.
//Code -
function getVowelsCount(str)
{
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
console.log(count);
}
Upvotes: 4
Reputation: 10282
(A)
const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;
(B)
const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;
countVowels("Stackoverflow") // 4
Upvotes: 1
Reputation: 1938
As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.
function vowelCount(str){
let splitString=str.split('');
let obj={};
let vowels="aeiou";
splitString.forEach((letter)=>{
if(vowels.indexOf(letter.toLowerCase())!==-1){
if(letter in obj){
obj[letter]++;
}else{
obj[letter]=1;
}
}
});
return obj;
}
Upvotes: 2
Reputation: 4189
const containVowels = str => {
const helper = ['a', 'e', 'i', 'o', 'u'];
const hash = {};
for (let c of str) {
if (helper.indexOf(c) !== -1) {
if (hash[c]) {
hash[c]++;
} else {
hash[c] = 1;
}
}
}
let count = 0;
for (let k in hash) {
count += hash[k];
}
return count;
};
console.log(containVowels('aaaa'));
Upvotes: 2
Reputation: 2867
Short and ES6, you can use the function count(str);
const count = str => (str.match(/[aeiou]/gi) || []).length;
Upvotes: 5
Reputation: 29067
You can convert the given string into an array using the spread operator, and then you can filter()
the characters to only those which are vowels (case-insensitive).
Afterwards, you can check the length
of the array to obtain the total number of vowels in the string:
const vowel_count = string => [...string].filter(c => 'aeiou'.includes(c.toLowerCase())).length;
console.log(vowel_count('aaaa')); // 4
console.log(vowel_count('AAAA')); // 4
console.log(vowel_count('foo BAR baz QUX')); // 5
console.log(vowel_count('Hello, world!')); // 3
Upvotes: 4
Reputation: 72
This is the shortest solution
function getCount(str) {
return (str.match(/[aeiou]/ig)||[]).length;
}
Upvotes: 3
Reputation: 678
This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:
function vowelCount(str) {
return str.replace(/[^aeiou]/gi, "").length;
};
or if you prefer ES6
const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )
Upvotes: 4
Reputation: 81
count = function(a) {
//var a=document.getElementById("t");
console.log(a); //to see input string on console
n = a.length;
console.log(n); //calculated length of string
var c = 0;
for (i = 0; i < n; i++) {
if ((a[i] == "a") || (a[i] == "e") || (a[i] == "i") || (a[i] == "o") || (a[i] == "u")) {
console.log(a[i]); //just to verify
c += 1;
}
}
document.getElementById("p").innerText = c;
}
<p>count of vowels </p>
<p id="p"></p>
<input id="t" />
<input type="button" value="count" onclick="count(t.value)" />
Upvotes: 2
Reputation: 118
Just use this function [for ES5] :
function countVowels(str){
return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;
}
Will work like a charm
Upvotes: 1
Reputation: 92729
Convert the string to an array using the Array.from()
method, then use the Array.prototype.filter()
method to filter the array to contain only vowels, and then the length
property will contain the number of vowels.
const countVowels = str => Array.from(str)
.filter(letter => 'aeiou'.includes(letter)).length;
console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
console.log(countVowels('test')); // 1
console.log(countVowels('ddd')); // 0
Upvotes: 12
Reputation: 32222
You can actually do this with a small regex:
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}
This just matches against the regex (g
makes it search the whole string, i
makes it case-insensitive) and returns the number of matches. We check for null
incase there are no matches (ie no vowels), and return 0 in that case.
Upvotes: 37
Reputation: 353
function countVowels(subject) {
return subject.match(/[aeiou]/gi).length;
}
You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.
Upvotes: 7