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

浏览器兼容性

另见