const haystack = "반갑습니다! 코딩에브리바디입니다.";
const needle = "코딩";

const isNeedle = haystack.includes(needle); // true

if (isNeedle) {
    console.log(`문자열에 '${needle}'이 포함되어 있습니다.`);
} else {
    console.log(`문자열에 '${needle}'이 포함되어 있지 않습니다.`);
}

// 출력: "문자열에 '코딩'이 포함되어 있습니다."
str.includes(searchString[, position])
const haystack = "Hello, World!";
const needle = "world";

const isNeedle = haystack.includes(needle); // false

if (isNeedle) {
    console.log(`문자열에 '${needle}'가 포함되어 있습니다.`);
} else {
    console.log(`문자열에 '${needle}'가 포함되어 있지 않습니다.`);
}

// 출력: "문자열에 'world'이 포함되어 있지 않습니다."
const haystack = "Hello, World!";
const needle = /Hello/; // 정규식이 아니어야 합니다. TypeError가 발생합니다.

const isNeedle = haystack.includes(needle);

if (isNeedle) {
    console.log(`문자열에 '${needle}'가 포함되어 있습니다.`);
} else {
    console.log(`문자열에 '${needle}'가 포함되어 있지 않습니다.`);
}
const haystack = "환영합니다.";
const needle = "";

const isNeedle = haystack.includes(needle);

console.log(isNeedle); // 빈 문자열은 항상 true를 반환합니다.
const txt = "나는 사과와 바나나를 좋아해요.";
const searchTerm = "사과";

if (txt.includes(searchTerm)) {
    console.log(`텍스트에 '${searchTerm}' 단어가 포함되어 있습니다.`);
} else {
    console.log(`텍스트에 '${searchTerm}' 단어가 포함되어 있지 않습니다.`);
}

// 출력: "텍스트에 '사과' 단어가 포함되어 있습니다."
const content = '이 문장에는 원치 않는 단어가 포함되어 있습니다.';
const unwantedWords = ['원치 않는', '나쁜', '부적절한'];

unwantedWords.forEach(unwantedWord => {
    if (content.includes(unwantedWord)) {
        let fillteredContent = content.replace(unwantedWord, "***");
        console.log(fillteredContent);
    }
});

// 출력: "이 문장에는 *** 단어가 포함되어 있습니다."
// 대소문자 구분 없이 'hello' 문자열 찾기
const searchStr = "hello";
const str = "Hello, world! hello, universe!".toLowerCase();

let count = 0;
let startIndex = 0;

while (str.includes(searchStr, startIndex)) {
    count++;
    startIndex = str.indexOf(searchStr, startIndex) + 1;
}

console.log("찾는 문자열의 반복 횟수:", count);
// 출력: 찾는 문자열의 반복 횟수: 2
문자열 includes() 함수의 브라우저 호환성
메서드
데스크탑 Chrome
Chrome
데스크탑데스크탑 Edge
Edge
데스크탑 Firefox
Firefox
Safari
Safari
includes() 41 12 40 9

caniuse.com에서 더 자세한 정보를 확인해 보세요.