AppDividend
Latest Code Tutorials

Javascript String StartsWith: String.prototype.startsWith()

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.

Javascript String StartsWith()

Javascript String startsWith() is an inbuilt function that determines whether the 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.

Syntax

The syntax of String startsWith() is following.

str.startsWith(searchString[, position])

Parameters

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.

Javascript String StartsWith Example

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.

String.prototype.startsWith() Tutorial

Finally, Javascript String startsWith() example 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.