Open In App

What is startsWith() Method in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, the startsWith() method is used to determine whether a string starts with a specified substring. It returns true if the string begins with the characters of the specified substring, and false otherwise.

Syntax:

string.startsWith(searchString, position)
  • string: The string to be searched.
  • searchString: The substring to search for at the beginning of string.
  • position (optional): The position within the string at which to begin the search. Default is 0.

Example: Here, the startsWith() method is called on the str string to check if it starts with the substring “Hello”. Since “Hello” is present at the beginning of the string, the method returns true, which is then assigned to the variable startsWithHello.

Javascript




const str = "Hello, World!";
const startsWithHello = str.startsWith("Hello");
 
console.log(startsWithHello); // Output: true


Output

true


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads