ES6+ startsWith()
1. 前言
在 ES5 中用于查找字符串的方法很少,上一节 我们学习了 includes()
方法,它是针对整个字符串进行查找的,本节要介绍 ES6 的字符串新增方法 startsWith()
,该方法用来判断当前字符串是否以给定的字符串作为开头。
字符串查找是有一定的算法的,虽然用 includes()
方法可以判断,无疑只查找字符串的开头算法的时间复杂度是很低的,但是使用 includes()
就需要对整个字符串进行查找,时间复杂度也会很高。在查找长字符串时也会比较耗费性能,虽然在测试过程中这种差别几乎可以被忽略,但是它的语义化让我们的代码可读性更高。
2. 方法详情
使用语法:
str.startsWith(searchString[, position])
参数说明:
实例:
const str1 = 'I love imooc.';
console.log(str1.startsWith('I')); // true
console.log(str1.startsWith('I', )); // false
3. 使用场景
3.1 一个参数
var str = "I love imooc.";
console.log(str.startsWith("I love")); // true
console.log(str.startsWith("imooc")); // false
console.log(str.startsWith("eimooc")); // false
3.2 两个参数
var str = "I love imooc.";
console.log(str.startsWith("love", )); // false
console.log(str.startsWith("ove", )); // true