JavaScript中的字符串是一种不可变的字符序列。includes()是字符串工具的一个方法,它用于判断一个字符串是否包含在另一个字符串中,并返回true或false。
二、语法
str.includes(searchString[, position])

三、参数阐明
searchString: 必需。要在str中搜索的字符串。
position: 可选。搜索的起始位置,默认值为0。
四、利用实例
// 示例2:指定起始位置搜索
let str2 = 'The quick brown fox jumps over the lazy dog.';
alert(str2.includes('fox', 20)); // output: false
alert(str2.includes('fox', 4)); // output: true
// 示例3:结合模板字符串利用
let str3 = 'JavaScript';
if (str3.includes('Script')) {
alert(`The string "${str3}" contains "Script".`);
} else {
alert(`The string "${str3}" does not contain "Script".`);
}
五、把稳事变
1、includes()方法区分大小写。
2、如果搜索字符串为空,则返回true。
3、如果指定的起始位置大于或即是字符串长度,则始终返回false。
六、常用在哪里
includes()方法常用于在字符串中搜索特定的子字符串。它用于验证用户输入是否包含特定的字符或单词,也可以用于搜索字符串数组中的元素。此外,它还可以用于过滤和排序字符串数组等方面。