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

 

posted @ 2018-03-09 21:58  ArthurWong  阅读(11266)  评论(0编辑  收藏  举报