大网数据广告活动
Web 标准与前端开发

String.prototype.includes()

· 52CE 我爱测

String 值的 **`includes()`** 方法执行区分大小写的搜索,以确定是否可以在一个字符串中找到另一个字符串,并根据情况返回 `true` 或 `false`。

String 值的 includes() 方法执行区分大小写的搜索,以确定是否可以在一个字符串中找到另一个字符串,并根据情况返回 true 或 false。

JavaScript Demo: String.includes()

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"

语法

includes(searchString)
includes(searchString, position)

参数

  • searchString
    • : 一个要在 str 中查找的字符串。不能是正则表达式。所有非正则表达式的值都会被强制转换为字符串,因此如果该参数被省略或传入 undefined,includes() 方法会在字符串中搜索 "undefined",这通常不是你想要的。
  • position
    • : 在字符串中开始搜索 searchString 的位置。默认值为 0。

返回值

如果在给定的字符串中找到了要搜索的字符串(包括 searchString 为空字符串的情况),则返回 true,否则返回 false。

异常

描述

此方法可以帮你判断一个字符串是否包含另外一个字符串。

区分大小写

includes() 方法是区分大小写的。例如,下面的表达式会返回 false:

"Blue Whale".includes("blue"); // 返回 false

你可以通过将原字符串和搜索字符串全部转换为小写来解决这个约束:

"Blue Whale".toLowerCase().includes("blue"); // 返回 true

示例

使用 includes()

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

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。