JavaScript 中 startsWith() 方法的重要性是什么?
javascriptobject oriented programmingfront end technology更新于 2025/6/5 23:40:17
要知道字符串是否以特定字符或字符串开头,请使用 indexOf() 方法。但在高级应用程序中,此方法已过时。因此,ES6 为我们提供了 startsWith() 方法来执行这些高级任务。
在下面的示例中,使用 IndexOf() 方法查找字符串是否以特定字符开头。
示例
<html>
<body>
<script>
var text = 'Tutorialspoint'
document.write(text.indexOf('T') === 0);
</script>
</body>
</html>
输出
true
在下面的例子中,不使用 indexOf() 方法,而是使用 startsWith() 方法来查找字符串是否以特定字符串开头。
示例
<html>
<body>
<script>
var text = 'Tutorialspoint'
document.write(text.startsWith('Tu'));
</script>
</body>
</html>
输出
true
我们还可以发送 index 来搜索特定字符串,无论它是否位于该特定位置。
在下面的示例中,Indexes 作为参数发送到 startsWith() 方法,以查明特定字符串是否位于这些特定索引处。
示例
<html>
<body>
<script>
var text = 'Tutorialspoint'
document.write(text.startsWith('Tut', 0));
document.write("</br>");
document.write(text.startsWith('ut', 1));
document.write("</br>");
document.write(text.startsWith('t', 2));
</script>
</body>
</html>
输出
true true true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

