Algorithm 5 - [JS] Vowel Count

luneah·2021년 12월 4일
0

Algorithm CodeKata

목록 보기
5/13
post-thumbnail

Vowel Count

Return the number (count) of vowels in the given string.

We will consider a, e, i, o, u as vowels for this Kata (but not y).

The input string will only consist of lower case letters and/or spaces.

📌 Needs ) 주어진 문자열에서 모음(a, e, i, o, u)의 개수를 반환하라.
📁 Sol )
1. 모음 array 작성
2. for...of문 사용
3. if문 : 조건에 해당하면 개수 +1
4. includes : 배열 항목 중 특정 값이 포함되어 있는지 여부 확인

function getCount(str) {
  var vowelsCount = 0;
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  for(let char of str) {
    if(vowels.includes(char)) {
      vowelsCount++
    }
  }
  
  return vowelsCount;
}

💡 Other ways to solve )

  • str.match : 문자열이 정규식과 매치되는 부분을 검색
    • 정규식에 g 플래그가 포함되어있지 않으면, str.match() 는 RegExp.exec()와 같은 결과를 반환
    • 정규식에 g 플래그가 포함되어 있으면, 일치는 객체가 아닌 일치하는 하위 문자열을 포함하는 Array를 반환
function getCount(str) {
  return (str.match(/[aeiou]/ig)||[]).length;
}
profile
하늘이의 개발 일기

0개의 댓글