countVowels.js (7kyu 03)

Codewars 알고리즘 풀이


Description

  • Return the number of vowels in the given string.
    • 주어진 문자열에서 모음(vowel)의 수를 반환한다.
  • The input string will only consist of lower case letters and/or spaces.
    • 문자열은 소문자와 공백으로만 구성된다.



Solution 01

function countVowels(str) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  let count = 0;
  
  for (let i = 0; i < str.length; i++) {
    for (let j = 0; j < vowels.length; j++) {
      if (str[i] === vowels[j]) {
        count++;
      }
    }
  }
  
  return count;
}

countVowels('codewars');     // 3 (o, e, a)
countVowels('hello world');  // 3 (e, o, o)
countVowels('abracadabra');  // 5 (a, a, a, a, a)


Solution 02

function countVowels(str) {
  const vowels = 'aeiou';
  let count = 0;
  
  for (let i = 0; i < str.length; i++) {
    if (vowels.indexOf(str[i]) !== -1) {
      count++;
    }
  }
  
  return count;
}

countVowels('codewars');     // 3 (o, e, a)
countVowels('hello world');  // 3 (e, o, o)
countVowels('abracadabra');  // 5 (a, a, a, a, a)


Solution 03

function countVowels(str) {
  return str.split('').filter(i => 'aeiou'.includes(i)).length;
}

countVowels('codewars');     // 3 (o, e, a)
countVowels('hello world');  // 3 (e, o, o)
countVowels('abracadabra');  // 5 (a, a, a, a, a)


Solution 04

function countVowels(str) {
  return str.replace(/[^aeiou]/g, '').length;
}

countVowels('codewars');     // 3 (o, e, a)
countVowels('hello world');  // 3 (e, o, o)
countVowels('abracadabra');  // 5 (a, a, a, a, a)


Solution 05

function countVowels(str) {
  return (str.match(/[aeiou]/g) || []).length;
}

countVowels('codewars');     // 3 (o, e, a)
countVowels('hello world');  // 3 (e, o, o)
countVowels('abracadabra');  // 5 (a, a, a, a, a)