This post will illustrate the procedure to verify the string starts with another specified string.
How to Check/Verify if a String “StartsWith” Another String?
To verify if a string starts with the other given string, use the given methods:
Method 1: Check if a String “StartsWith” Another String Using “startsWith()” Method
In JavaScript, you can determine if a string starts with another string utilizing the “startsWith()” method. This method gives a Boolean value indicating whether the string starts with a particular string or character. If the string begins with the given/specified string, it outputs true, else, it gives false. Moreover, it is a case-sensitive method.
Syntax
Use the following syntax to verify if a string starts with another specified string:
Example
Create a string named “str” that will check whether it is started with the other string:
Create another string “str1” that is a search string:
Now, check whether the string “str” starts with the string “str1” using the “startsWith()” method:
It can be observed that the output gives “false” because the startsWith() method is a case-sensitive method and the “str1” stores “welcome” while the “str” starts with “Welcome”:
Here, we will store “Welcome” in the “str1” to check the “str” starts with it or not:
The output displays “true” which means “str” starts with the “str1”:
Method 2: Check if a String “StartsWith” Another String Using “indexOf()” Method
Another way to determine if the string starts with another string is to use the “indexOf()” method. It checks whether the specified string or character is found at the beginning/start of the string. If it is, the indexOf() method gives 0, which means “true”, so the expression outputs “true”.
Syntax
Follow the below-mentioned syntax for the indexOf() method to verify the strings starts with another string:
Example
Store “welcome” to the search string “str1”:
Invoke the “indexOf()” method by passing the search string. If the resultant value is equivalent to the “0”, it outputs “true” which means the string starts with the search string, else it outputs “false”:
Output
The above output shows “false” which means str does not start with the str1.
Conclusion
To verify if a string starts with another given string, use the “startsWith()” method or the “indexOf()” method. The “startsWith()” method is the most efficient and commonly utilized approach. This post illustrated the procedure to verify the string starts with another specified string.