ES6--javascript判断一个字符串是否存在另一个字符串中

es5中我们经常使用indexof()方法来判断一个字符串是否包含另外一个字符串中。

 

如果存在则返回匹配到的第一个索引值。如果没有则返回 -1。所以,判断一个字符串是否包含另外一个字符串中只需要判断是否为-1就行。-1代表不存在。

 

例如:

let str = 'Hello World!';
console.log(str.indexOf('H'));//0  str中"H"的出现的第一个索引为0
console.log(str.indexOf('o'));//4  str中"o"第一个出现的位置的索引为4
console.log(str.indexOf('a'));//-1 没找到,返回-1

 

虽然Es5中该方法经常使用,但是Es6提供了更加便捷的方法。

 

1. str.includes('');

有返回true,没有返回false。也不用为记住-1而发愁了!!

let str = 'Hello World!';
console.log(str.includes('H'));//true
console.log(str.includes('a'));//false

 

2.startsWith()

判断该字符串是否为某个字符串的首位。有就是true,不是就是false。

let str = 'Hello World!';
console.log(str.startsWith('H'));//true
console.log(str.startsWith('Hello'));//true
console.log(str.startsWith('e'));//false

 

3.endsWith()

和startsWith()相反。判断是否为末尾。

let str = 'Hello World!';
console.log(str.endsWith('!'));//true
console.log(str.endsWith('d!'));//true
console.log(str.endsWith('e'));//false

 

这三个方法都支持第二个参数,表示看是搜索的位置。

let str = 'Hello World!';
console.log(str.includes('World',5));//true 从索引5(包含索引5)开始搜索
console.log(str.includes('World',7));//false
console.log(str.startsWith('lo',3))//true
console.log(str.startsWith('H',3));//false
console.log(str.endsWith('el',3));//true 
endsWith()和上面两个不一样,它的第二个参数代表前几个。“Hel”,所以返回true

 

转载于:https://www.cnblogs.com/chinabin1993/p/8536591.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值