我们可以通过两种 方式在字符串中找到子 字符串 。一种方法是使用indexOf()方法,另一种方法是使用ES6方法。让我们详细讨论它们。includes()
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(str);
与indexOf()方法不同,此方法将检查我们提供的字符串是否存在。如果存在,则true将显示为输出,否则false将显示为输出。此方法也区分大小写。我们需要提供一个确切的字符串来检查其存在。
<html>
<body>
<script>
var company = "nhooo";
document.write(company.includes('Tutor'));
document.write("</br>");
document.write(company.includes('point'));
</script>
</body>
</html>false true