ES6, introduced in 2015, added the startsWith() method to the String object prototype. This means you can call startsWith() function on any string, provide a substring, and check if the result returns true or false.
The syntax of String startsWith() is following.
searchString: The characters to be searched for at the start of this string.
position: OptionalThe position in this string at which to begin searching for searchString; defaults to 0.
Let’s see the following example.
// app.js const str1 = 'Captain Marvel movie is somewhat boring'; console.log(str1.startsWith('Cap')); console.log(str1.startsWith('Marvel', 8));
See the output.
The String character starts with 0th position. So above will return the true. Let’s see a scenario where we get false.
// app.js const str1 = 'Captain Marvel movie is somewhat boring'; console.log(str1.startsWith('Marvel')); console.log(str1.startsWith('Marvel', 9));
See the below output.