在 javascript 中,有多少种方法可以在字符串中找到子字符串?
javascriptobject oriented programmingfront end technology更新于 2025/7/1 10:20:17
我们可以通过两种方法在字符串中找到子字符串。一种方法是使用 indexOf() 方法,另一种方法是使用 ES6 includes() 方法。让我们详细讨论一下它们。
indexOf()
语法
indexOf(str);
此方法尝试检查我们需要的子字符串的索引。如果有索引,即存在子字符串,则输出中将显示 true ,否则将显示 false 。此方法区分大小写。
示例
<html>
<body>
<script>
var company = "Tutorix";
document.write(company.indexOf('Tutor') !== -1);
document.write("</br>");
document.write(company.indexOf('tutor') !== -1);
</script>
</body>
</html>
输出
true false
includes()
语法
includes(str);
与 indexOf() 方法不同,此方法将检查我们提供的字符串是否存在。如果存在,则将显示 true 作为输出,否则将显示 false 作为输出。此方法还区分大小写。我们需要提供一个精确的字符串来检查其存在性。
示例
<html>
<body>
<script>
var company = "tutorialspoint";
document.write(company.includes('Tutor'));
document.write("</br>");
document.write(company.includes('point'));
</script>
</body>
</html>
输出
false true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

