We can find a substring inside a string in two ways. One way is using the indexOf() method and the other is using ES6 includes() method. let's discuss them in detail.
indexOf()
syntax
indexOf(str);
This method tries to check the index of the substring we need. If there is index, which means substring is present, then true will be displayed in the output else false will be displayed as output. This method is case sensitive.
Example
<html> <body> <script> var company = "Tutorix"; document.write(company.indexOf('Tutor') !== -1); document.write("</br>"); document.write(company.indexOf('tutor') !== -1); </script> </body> </html>
Output
true false
includes()
syntax
includes(str);
Unlike the indexOf() method, this method will check the string we provided whether it is present or not. If present then true will be displayed as output else false will be displayed as output. This method is also case sensitive. We need to provide an exact string to check its presence.
Example
<html> <body> <script> var company = "tutorialspoint"; document.write(company.includes('Tutor')); document.write("</br>"); document.write(company.includes('point')); </script> </body> </html>
Output
false true