Introduction
The startsWith()
method in JavaScript is used to check if a string begins with a specified string or character. This method returns a Boolean value, indicating whether or not the string begins with the specified string or character.
In this article, we discuss how to make use of the startsWith()
method in JavaScript.
Using the startsWith()
method
Search for first character
To use the startsWith()
method, you pass in the string or character that you want to search for as the first argument, and the string that you want to search in as the second argument. For example, to check if the string "JavaScript" begins with the letter "J", you would use the following code:
let str = "JavaScript";
if (str.startsWith("J")) {
console.log("Start Learning");
}
Output
Start Learning
In this code, the startsWith()
method is called on the str
variable, which contains the string "JavaScript". The method is passed the string "J" as its first argument, and str
as its second argument. If the string "JavaScript" begins with the letter "J", then the if
statement will be executed and the code inside it will run.
Search from specified position
You can also specify the position at which the startsWith()
method should start searching for the specified string or character. To do this, you pass in an additional integer argument after the string or character that you want to search for. For example, to check if the string "JavaScript" begins with the letters "Ja" starting at the second character, you would use the following code:
let str = "JavaScript";
if (str.startsWith("Ja", 1)) {
console.log("Start Learning");
} else {
console.log("Let's start either way.");
}
Output
Let's start either way.
In this code, the startsWith()
method is called on the str
variable, which contains the string "JavaScript". The method is passed the string "Ja" as its first argument, and str
as its second argument. The integer 1
is passed as the third argument, which specifies that the startsWith()
method should start searching for the string "Ja" at the second character of the str
string. If the string "JavaScript" begins with the letters "Ja" starting at the second character, then the if
statement will be executed and the code inside it will run.
Summary
As you can see, the startsWith()
method is a powerful and versatile tool for working with strings in JavaScript. Whether you need to check if a string or part of a string begins with a specific letter, number, or symbol.
References
String.prototype.startsWith() - JavaScript | MDN (mozilla.org)