To know Whether a string starts with a particular character or a string indexOf() method is used. But in the advanced applications, this method is obsolete. So, ES6 has provided us with startsWith() method to perform those advanced tasks.
In the following example, the IndexOf() method is used to find whether the string is started with a particular character or not.
Example
<html> <body> <script> var text = 'Tutorialspoint' document.write(text.indexOf('T') === 0); </script> </body> </html>
Output
true
In the following example, instead of indexOf() method, startsWith() method is used to find whether the string is started with a particular string or not.
Example
<html> <body> <script> var text = 'Tutorialspoint' document.write(text.startsWith('Tu')); </script> </body> </html>
Output
true
We can also send an index to search for a particular string whether it is there at that particular position or not.
In the following example, Indexes were sent as an argument to the startsWith() method to find out whether particular strings are at those particular indexes or not.
Example
<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>
Output
true true true