JavaScript startsWith Method: Check with what character your string starts with
In this tutorial, you will learn to check if your string starts with a certain set of characters or not using the startsWith() method in JavaScript.
JavaScript startsWith Method
The startsWith() string method is used to determine whether a string starts with some given substring or not.
If the string starts with a specified substring then it returns true if not then return false.
The method is applied on a string and the substring is passed as the first argument to the method.
const str = "Learning to code";
console.log(str.startsWith("to")); // false
console.log(str.startsWith("Learning")); // true
Syntax of startsWith method
The syntax of startsWith() string method in javascript is:
string.startsWith(search_string [ ,position])
The method accepts 2 arguments:
- search_string - It is the substring or a set of character to be searched at the starting of a given string.
- position (optional) - It is an optional argument that is the position in the string from where the search for the substring is started. The default value is 0.
startsWith Method Example
# Example 1: Using startsWith
method without position parameter.
Example
const str = "To do or not to do";
console.log(str.startsWith("do")); // false
console.log(str.startsWith("To")); // true
console.log(str.startsWith("T")); // true
console.log(str.startsWith("To ")); // true
In the above example first, we check for substring 'do' which is not the starting of the calling string and return false
, then we check for substring 'To' and method return true
. The method also returns true
for 'T' and 'To ' because the method does not count the first word but count anything that is at starting of the string.
# Example 2: Using startsWith
method with position parameter.
Example
const str = "To do or not to do";
console.log(str.startsWith("do", 3)); // true
console.log(str.startsWith("To", 0)); // true
console.log(str.startsWith("T0", 2)); // false
When using the position parameter, the starting substring is checked from a given position. So when we check to start of the string by giving position 3 it returned true
.
Case-sensitivity
The startsWith() method is case sensitive, which means it treats string with the same characters but the different case as different.
Look out the following example:
const str = "Learn to code";
console.log(str.startsWith("Learn")); // true
console.log(str.startsWith("LEARN")); // false
console.log(str.startsWith("learn")); // false
Points to remember:
- The startsWith() check whether or not a string starts with a specified substring.
- The startsWith() method performs a case-sensitive search on the string.