String.prototype.includes()

String 值的 includes() 方法执行区分大小写的搜索,以确定是否可以在该字符串中找到给定字符串,并根据需要返回 truefalse

¥The includes() method of String values performs a case-sensitive search to determine whether a given string may be found within this string, returning true or false as appropriate.

Try it

语法

¥Syntax

js
includes(searchString)
includes(searchString, position)

参数

¥Parameters

searchString

要在 str 内搜索的字符串。不能 是一个正则表达式。所有非正则表达式的值都是 强制为字符串,因此省略它或传递 undefined 会导致 includes() 搜索字符串 "undefined",这很少是你想要的。

position Optional

字符串中开始搜索 searchString 的位置。(默认为 0。)

返回值

¥Return value

true 如果在给定字符串中的任何位置找到搜索字符串,包括 searchString 为空字符串时;否则,false

¥**true** if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false.

例外情况

¥Exceptions

TypeError

如果 searchString 是一个正则表达式 则抛出。

描述

¥Description

此方法可让你确定一个字符串是否包含另一个字符串。

¥This method lets you determine whether or not a string includes another string.

区分大小写

¥Case-sensitivity

includes() 方法区分大小写。例如,以下表达式返回 false

¥The includes() method is case sensitive. For example, the following expression returns false:

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

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

¥You can work around this constraint by transforming both the original string and the search string to all lowercase:

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

示例

¥Examples

使用包含()

¥Using 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

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.includes

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看