传统上,javaScript只有indexOf方法来确定字符串中是否包含了另一个字符串:
var str = "hello world"
let val = str.indexOf("w")==-1?false:true
es6又提供了三种方法:
1.includes() 返回bool值,表示是否找到参数字符串
let val2 = str.includes("hello")
2.startsWith(): 返回布尔值, 表示参数字符串是否在源字符串的头部
let val3 = str.startsWith("ello") //false
3.endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部
let val4 = str.endsWith("ld")
这三种方法都支持第二个参数,表示开始搜索的位置
str.startsWith(’world’, 6) //true
str.endsWith(’hello’, 5) // true
str.includes (’ hello ’, 6) // false
上面的代码表示,使用第二个参数 n 时, endsWith 的行为 与其 他两个方法有所不同 。 它 针对前 n 个字符,而其他两个方法针对从第 n 个位置到字符串结束位置之间的字符。