我们可以通过几种方式在javascript的字符串中找到子字符串?

我们可以通过两种 方式在字符串中找到子 字符串 。一种方法是使用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


include()

语法

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