JavaScript教程-JavaScript 的 string includes() 方法

JavaScript 中的 includes() 方法用于确定给定字符串中是否包含指定的子字符串。它是区分大小写的方法。它返回布尔值,即 true 或 false。如果字符串包含指定的子字符串,它将返回 true,否则返回 false。
它不会改变原始字符串的值。
语法
以下语法表示 includes() 方法:
string.includes(searchValue, start);
参数值
该方法的参数值定义如下:
searchValue: 这是一个必需的参数。它是要搜索的子字符串。
start: 这是一个可选参数。它表示要从字符串中的哪个位置开始搜索。其默认值为 0。当省略时,搜索将从字符串的初始位置开始,即从 0 开始。
让我们通过一些示例了解 includes() 方法。
示例1
这是一个简单的示例,用于确定给定字符串是否包含指定的子字符串。在这里,我们声明一个变量 str 并将字符串值 'Welcome to the javaTpoint.com' 赋给它。然后,我们使用 includes() 方法来确定给定子字符串('to')是否存在。
在这里,我们没有定义开始搜索的位置。因此,搜索将从字符串的初始位置开始。
<!DOCTYPE html>
<html>
<head>
<title>includes() method</title>
</head>
<body>
<h1>Hello world :):)</h1>
<h3>This is an example of using the JavaScript's string includes() method.</h3>
<script>
let str = "Welcome to the javaTiku.cn";
document.write("<b> The given string is: </b>", str);
document.write("<br>");
let res = str.includes('to');
document.write("<b> The result is: </b>", res);
</script>
</body>
</html>
示例2
在这个示例中,我们正在确定 includes() 方法是否区分大小写。给定的字符串是 'Welcome to the javaTpoint.com'。我们正在给定字符串中搜索子字符串 'TO'。
虽然单词 'to' 在给定字符串中存在,但方法是区分大小写的,因此它将返回布尔值 *false*。
<!DOCTYPE html>
<html>
<head>
<title>includes() method</title>
</head>
<body>
<h1>Hello world :):)</h1>
<h3>This is an example of using the JavaScript's string includes() method.</h3>
<p>Here, we are searching for the substring <b>'TO'</b> in the given string.</p>
<script>
let str = "Welcome to the javaTiku.cn";
document.write("<b> The given string is: </b>", str);
document.write("<br>");
let res = str.includes('TO');
document.write("<b> The result is: </b>", res);
</script>
</body>
</html>
示例3
在这个示例中,我们定义了开始搜索的位置。因此,搜索将从指定位置开始。
<!DOCTYPE html>
<html>
<head>
<title>includes() method</title>
</head>
<body>
<h1>Hello world :):)</h1>
<h3>This is an example of using the JavaScript string includes() method.</h3>
<script>
let str = "Welcome to the javaTiku.cn";
document.write("<b> The given string is: </b>", str);
document.write("<br>");
let res = str.includes('the', 10);
document.write("<b> The result of str.includes('the', 10) is : </b>", res);
</script>
</body>
</html>