- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is importance of startsWith() method in JavaScript?
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