[codewars] Vowel Count

sekoong·2024년 9월 18일

CodeWars

목록 보기
3/6
post-thumbnail

7kyu

- Description

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.

- My Solution

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

- Better solution

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

- concepts

  1. match
  • 개념
    match는 JavaScript에서 문자열에서 정규 표현식에 매치되는 부분을 찾을 때 사용하는 메서드이다.
    이 메서드는 문자열에서 정규 표현식과 일치하는 모든 부분들을 배열로 반환한다.

  • 문법
    [] : 문자 클래스를 정의하여 그 안에 포함된 문자 중 하나와 일치합니다. 특정 문자 집합을 찾을 때 유용합니다.
    패턴의 반복 : a+ : 하나 이상 반복되는 패턴을 찾음
    선택 a|b : a 또는 b와 일치합니다.

  • 사용법


// 문자열과 일치
const str = 'Hello world';
const regex = /Hello/gi;
const result = str.match(regex);

console.log(result); //["Hello"]; 문자열 Hello와 일치

// 문자열 중 하나와 일치
let str1 = "Hello world!";
let result1 = str1.match(/[aeiou]/ig) || []; 
console.log(result1);  // ["e", "o", "o"] 포함된 문자 중 하나와 일치

solution review

  • 정규표현식 관련 메소드 정리하기...
  • 갈길이 멀군..

0개의 댓글