ES6+知识点汇总(6)— 新增常用字符串方法详解

十三、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()

  1. includes是区分大小写的
'hello es6'.includes('hello');  // true
'hello es6'.includes('Hello');  // false 
  1. includes传递一个参数时会从第一个字符开始查找
const str = "hello word!";

console.log(str.includes("hello"));    // true
console.log(str.includes("word"));     // true
console.log(str.includes("eword"));    // false 
  1. 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的注意事项
  1. includes会做类型转换
const str = '2022';
 
str.includes('2');  // true
str.includes(2);    // true 
  • 在判断字符串2和数字2时都能返回true,是因为includes会把数字转换成字符串然后再执行查找
  1. 不能对Number类型直接使用
let numStr = 2020;
numStr.includes(2);    // Uncaught TypeError: numStr.includes is not a function 
  • includes如果直接使用在数值类型上会报语法错误ÿ
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值