传统上javasc提供了indeof的方法用来确定一个字符串是否包含一个字符串,但es6有提供新的方法。
1.首先我们回顾一下传统的indexof方法
indexof()方法可以判断一个字符串是否包含另一个字符串,如果包含返回的是该字符串的下标,如果存在则返回-1
var arr="asdfg"
var a=arr.indeoxf("s")
var b=arr.indexof("a")
var c=arr.indexof("w")
console.log(a)//1
console.log(b)//0
console.log(c)//-1
注:lastIndexOf和fistIndexOf与indexOf的用法一样,只不过lastIndexOf是返回该字符串最后一次出现的位置的下标,而firstIndexOf是返回该字符串第一次位位置的下标,三者存在都是有返回下标,不存在返回-12。
2.es6新提供的三种方法
1.includes():返回布尔值,表示是否含有字符串
2.staartsWith():返回布尔值,表示参数字符串是否在源字符串的头部
3.endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部。
var s="hello word!"
console.log(s.indexof("h"))//0
console.log(s.startsWith("h"))//true
console.log(s.endsWith("!"))//true
console.log(s.includes("h"))//true
2.这三个方法都支持第二个参数
var s="hello word!"
console.log(s.startsWith("word",6))//true
console.log(s.endsWith("hello",5))//true
console.log(s.includes("hello,6"))//false
注:在使用第二个参数n时,endsWith和其他两个方法有所不同,他针对前n个字符,而其他两个方法针对从第n个位置到字符串结束位置之间的字符