判断某个字符串是否出现在当前字符串中
indexOf()lastIndexOf()includes()startsWith()endsWith()match()
indexOf()
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置; 如果没有找到匹配的字符串则返回 -1 let str = 'abcdeedcba'
console.log(str.indexOf('a'), str.indexOf('f')) // 0 -1
lastIndexOf()
latIndexOf()方法可返回某个指定的字符串值在字符串中最后一次出现的位置; 如果没有找到匹配的字符串则返回 -1 let str = 'abcdeedcba'
console.log(str.lastIndexOf('a'), str.lastIndexOf('f')) // 9 -1
includes()
includes()方法为es6新增的遍历字符串的方法; str.includes(sstr,index)
sstr:指定的字符串;index:从那个下标开始扫描(默认0) includes()可返回某个指定的字符串是否在当前字符串出现过
出现过-true没出现过-false let str = 'abcdeedcba'
console.log(str.includes('c'), str.includes('c', 8), str.includes('f')) // true falae false
startsWith()
startsWith()方法为es6新增的遍历字符串的方法; str.startsWith(sstr,index)
sstr:指定的字符串;index:从那个下标开始扫描(默认0) startsWith()可返回参数字符串是否在原字符串的头部 let str = 'abcdeedcba'
console.log(str.startsWith('c'), str.startsWith('c',2), str.startsWith('f')) // false true false
endsWith()
endsWith()方法为es6新增的遍历字符串的方法; str.endsWith(sstr,index)
sstr:指定的字符串;index:从下标为0开始扫描到哪个下表(默认最后一个字符) endsWith()可返回参数字符串是否在原字符串的尾部 let str = 'abcdeedcba'
console.log(str.endsWith('c'), str.startsWith('c',str.length-3), str.startsWith('f')) // false true false
match()
match方法详解
可以查看指定字符串在当前字符串中出现过几次
参考阅读
发表评论