[javascript] 문자열 내 특정 문자 개수 세기

1. for loop를 활용한 방법

function countChar(str, char) {
    let count = 0;
    for (let i = 0; i < str.length; i++) {
        if (str[i] === char) {
            count++;
        }
    }
    return count;
}

const str = "Hello World";
const char = "o";
const result = countChar(str, char);
console.log(`"${str}" 문자열 내에서 "${char}" 문자는 총 ${result}개 있습니다.`);

2. split()과 filter() 메서드를 활용한 방법

function countChar(str, char) {
    return str.split('').filter(ch => ch === char).length;
}

const str = "Hello World";
const char = "o";
const result = countChar(str, char);
console.log(`"${str}" 문자열 내에서 "${char}" 문자는 총 ${result}개 있습니다.`);

3. 정규 표현식을 활용한 방법

function countChar(str, char) {
    const regex = new RegExp(char, 'g');
    return str.match(regex).length;
}

const str = "Hello World";
const char = "o";
const result = countChar(str, char);
console.log(`"${str}" 문자열 내에서 "${char}" 문자는 총 ${result}개 있습니다.`);

위 예제들은 모두 주어진 문자열 내에서 특정 문자의 개수를 세는 방법을 보여주고 있습니다. 각각의 방법은 장단점이 있으니 상황에 맞게 선택하여 사용하시면 됩니다.

참고 자료: