- Code and Explanation
- Closing thoughts
This method is commonly used to check if the entered string contains a substring. Although there are other methods that can be used to find substrings, the startsWith() method is specifically used to check the start of a string.
- SearchString - Required, the character/ string to search
- Position - Optional, used to specify the position to begin the search
The method returns a boolean true if it finds the SearchString and false if it doesn’t.
Code and Explanation:
In this section, we look at the implementation of the startsWith method.
const str_1 = 'Join our freelancer community'; console.log(str_1.startsWith('Join')); // Output: true console.log(str_1.startsWith('Join', 3)); // Output: false console.log(str_1.startsWith('our', 5)); // Output: true
In the above code, the first statement returns true as the string begins with ‘Join”. However, in the second statement, we have passed a position argument. Hence the startsWith operator starts searching from the 3 index and returns a false.
Similarly, the last statement returns true as ‘our’ start’s in the 5th index.
However, in case you are just looking to find a substring, I would recommend using the includes() method.
Once you are done practicing using the startsWith methods you can try the endsWith method.