String.prototype.includes()
String 值的 includes() 方法執行區分大小寫的搜尋,以確定給定字串是否包含在此字串中,並相應地返回 true 或 false。
試一試
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。
異常
描述
此方法允許您確定一個字串是否包含另一個字串。
區分大小寫
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 |
瀏覽器相容性
載入中…