十三、ES6+字符串方法
13-1、includes
在ES5中,如果想要查找一个字符串中是否包含另一个字符串,一般会使用indexOf、lastIndexOf、search:
- 使用indexOf()会发返回查询后第一次出现指定字符串的索引,如果未找到则返回-1
- ES6新增的includes()方法用来替代indexOf()的不足,能够更好的去判断,而不是需要根据返回的索引进一步判断
13-1-1、includes的基本使用方法
includes()方法主要用于查询字符串,判断一个字符串是否包含另一个字符串,其返回值是true / false
语法:
str.includes(searchString[, position])
参数说明:
参数 | 描述 |
---|---|
searchString | 需要查找的目标字符串 |
position | (可选)从当前字符串的哪个索引位置开始查找,默认值为0 |
const str = 'hello world';
console.log(str.includes('hello')); // true
console.log(str.includes('hello', 2)); // false
要注意的是:
当传递一个空字符串或不传递字符串时,要查询的内容会被强制转换为“undefined” ,然后再在字符串中去匹配“undefined”
'undefined'.includes(''); // true
'undefined'.includes(); // true
'123'.includes(); // false
13-1-2、includes的使用场景
includes()方法的引入是为了代替indexOf()
- includes是区分大小写的
'hello es6'.includes('hello'); // true
'hello es6'.includes('Hello'); // false
- includes传递一个参数时会从第一个字符开始查找
const str = "hello word!";
console.log(str.includes("hello")); // true
console.log(str.includes("word")); // true
console.log(str.includes("eword")); // false
- includes传递两个参数时会将第二个参数作为索引的位置开始查找(包含当前索引位置)
- 当索引为负数时,则会认为从索引为0的位置开始查找
const str = "hello word!";
console.log(str.includes("llo", 3)); // fasle
console.log(str.includes("llo", 2)); // true
console.log(str.includes("wor", 6)); // true
console.log(str.includes("ord!", -1)); // true
13-1-3、includes的注意事项
- includes会做类型转换
const str = '2022';
str.includes('2'); // true
str.includes(2); // true
- 在判断字符串2和数字2时都能返回true,是因为includes会把数字转换成字符串然后再执行查找
- 不能对Number类型直接使用
let numStr = 2020;
numStr.includes(2); // Uncaught TypeError: numStr.includes is not a function
- includes如果直接使用在数值类型上会报语法错误ÿ