前言
JavaScript string的这三个方法都是根据参数返回true或false
一、includes
includes() 方法判断一个字符串中是否包含传入的参数字符串,如果有返回true,否则返回false
语法:includes(valueStr, [fromIndex] )
valueStr:搜索的字符串
fromIndex:从当前字符串的哪个索引位置开始搜索,默认值为0
返回值:如果当前字符串包含搜索的字符串就返回true,否则返回false
const str = 'hello word'
str.includes('o') // true
str.includes('e', 5) // false
二、startsWith
startsWith() 方法判断一个字符串是否以另一个字符串开始,如果是返回true,否则返回false
语法:startsWith(valueStr, [ fromIndex ])
valueStr:要搜索的字符串
fromIndex:从当前字符串的哪个索引位置开始搜索,默认值为0
返回值:如果当前字符串以搜索的字符串开头返回true否则返回false
const str = 'hello word'
str.startsWith('he') // true
str.startsWith('he', 5) // false
str.startsWith('wo', 6) // true
三、endsWith
当前字符串是否以搜索的字符串结束,如果是返回true否则返回false
语法:str.endsWith(valueStr,[fromIndex])
valueStr:要搜索的字符串
fromIndex:在当前的字符串中的哪个索引位置向前搜索,默认为str.length
返回值:当前字符串是否以要搜索的字符串结束,如果是返回true否则返回false
const str = 'hello word'
str.endsWith('rd') // true
str.endsWith('lo', 5) // true
str.endsWith('lo', 6) // false
总结
这是es6新增的三个JavaScript string的方法,根据参数的不同返回true或者false。如果传入了第二个参数fromIndex,endsWith的处理方法和其他两个有所不同,endsWith搜索的是前fromIndex个字符,其他两个搜索的是从fromIndex到字符串结尾