String.prototype.includes()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

String 值的 includes() 方法執行區分大小寫的搜尋,以確定給定字串是否包含在此字串中,並相應地返回 truefalse

試一試

const sentence = "The quick brown fox jumps over the lazy dog.";

const word = "fox";

console.log(
  `The word "${word}" ${
    sentence.includes(word) ? "is" : "is not"
  } in the sentence`,
);
// Expected output: "The word "fox" is in the sentence"

語法

js
includes(searchString)
includes(searchString, position)

引數

searchString

要在 str 中搜索的字串。不能是 正則表示式。所有不是正則表示式的值都會被 強制轉換為字串,因此省略它或傳遞 undefined 會導致 includes() 搜尋字串 "undefined",這通常不是你想要的。

position 可選

在字串中開始搜尋 searchString 的位置。(預設為 0。)

返回值

如果搜尋字串在給定字串的任何位置找到,包括 searchString 是空字串時,則為 true;否則為 false

異常

TypeError

如果 searchString 是正則表示式,則丟擲此錯誤。

描述

此方法允許您確定一個字串是否包含另一個字串。

區分大小寫

includes() 方法區分大小寫。例如,以下表達式返回 false

js
"Blue Whale".includes("blue"); // returns false

您可以透過將原始字串和搜尋字串都轉換為小寫來解決此限制

js
"Blue Whale".toLowerCase().includes("blue"); // returns true

示例

使用 includes()

js
const str = "To be, or not to be, that is the question.";

console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false
console.log(str.includes("")); // true

規範

規範
ECMAScript® 2026 語言規範
# sec-string.prototype.includes

瀏覽器相容性

另見