JavaScript startsWith Method


In this tutorial, you will learn how to check if a given string starts with a character sequence or not. We get booleans value in terms of true or false using JavaScript startsWith method.

javascript startswith

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.

Example

var str = "Learning to code";

// using startsWith() method
console.log(str.startsWith("to")); // false
console.log(str.startsWith("Learning")); // true
Try It

Syntax of startsWith method

The syntax of startsWith() string method in javascript is:

string.startsWith(search_string)
string.startsWith(search_string, position)

The method accepts 2 arguments:

  1. search_string - It is the substring or a set of characters to be searched at the starting of a given string.
  2. 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
Try It

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 the method returns true. The method also returns true for 'T' and 'To ' because the method does not counts 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
Try It

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 strings with the same characters but the different cases 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
Try It

Conclusion

The startsWith can be used to determine whether a given string starts from another given string or not. The method is also case-sensitive.

Not just starting of the string you can identify the same thing for any position of string by passing the position as a second parameter in the method.

Happy coding!😇