js includes方法
JavaScript提供了includes
方法,用于判断一个字符串中是否包含指定的子字符串。本文将详细介绍includes
方法的用法及示例。
1. includes方法的基本用法
includes
方法属于字符串的方法,用于判断一个字符串是否包含指定的子字符串。它返回一个布尔值,表示是否包含。
该方法的语法如下:
str.includes(searchString[, position])
其中,searchString
为需要被搜索的子字符串,position
为可选参数,表示开始搜索的位置,默认值为0。若省略position
参数,则从字符串的开头开始搜索。
includes
方法区分大小写,即大写字母和小写字母被视为不同字符。
接下来,我们通过几个示例来理解includes
方法的具体用法。
2. includes方法的示例
示例一:判断字符串是否包含指定字符
我们首先通过一个简单的示例,来展示includes
方法判断字符串是否包含指定字符的功能。
let str = 'Hello World';
console.log(str.includes('o')); // true
console.log(str.includes('w')); // false
console.log(str.includes('llo')); // true
上述示例中,字符串'Hello World'
包含字符'o'
和子字符串'llo'
,分别返回true
。
示例二:指定开始搜索的位置
我们可以使用第二个参数position
来指定开始搜索的位置。下面的示例中,仅从索引为5的位置开始搜索。
let str = 'Hello World';
console.log(str.includes('W', 5)); // true
console.log(str.includes('o', 5)); // false
console.log(str.includes('W', 6)); // false
在上述示例中,'Hello World'
在索引5之后的子字符串中包含字符'W'
,返回true
。而从索引6开始的子字符串中,不包含字符'W'
,返回false
。
3. includes方法的兼容性
includes
方法属于ECMAScript 2015规范(ES6),因此在较老的浏览器中可能不被支持。事实上,includes
方法在IE11及之前的版本不被支持。
但是,我们可以通过使用polyfill来扩展旧版本的浏览器,使其支持includes
方法。下面是一个实现polyfill的示例代码:
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
上述代码中,我们创建了String.prototype.includes
方法的polyfill,使其在不支持includes
方法的浏览器中也可以使用。
4. 总结
includes
方法是JavaScript字符串对象的一个有用特性,用于判断一个字符串是否包含指定的子字符串。它返回一个布尔值,方便进行判断操作。
在使用includes
方法时,需要注意指定开始搜索的位置和字符串的大小写。在一些较旧的浏览器中,includes
方法可能不被支持,但是我们可以使用polyfill来扩展兼容性。