AppDividend
Latest Code Tutorials

Javascript String StartsWith Example | String.prototype.startsWith() Tutorial

0

Javascript String StartsWith Example | String.prototype.startsWith() Tutorial is today’s topic. The string startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate. It is checking if a string starts with another substring is a common thing to do. See how to perform this check in JavaScript.

Javascript String StartsWith Example

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.

str.startsWith(searchString[, position])

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));

The output is following.

 

Javascript String StartsWith Example

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));

The output is following.

 

String.prototype.startsWith() Tutorial

Finally, Javascript String.prototype.startsWith() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.