Javascript String startsWith()

The JavaScript String startsWith() method checks if a string begins with the characters of a specified string.

The syntax of the startsWith() method is:

str.startsWith(searchString, position)

Here, str is a string.

startsWith() Parameters

The startsWith() method takes in :

  • searchString - The characters to be searched for at the beginning of str.
  • position (optional) - The position in str to start searching for searchString. Default value is 0.

Return value from startsWith()

  • Returns true if the given characters are found at the beginning of the string.
  • Returns false if given characters are not found at the beginning of the string.

Note: The startsWith() method is case sensitive.

Example: Using startsWith() method

sentence = "Java is to JavaScript what Car is to Carpet.";

let check = sentence.startsWith("Java");
console.log(check); // true

let check1 = sentence.startsWith("Java is");
console.log(check1); // true

// case sensitive
let check2 = sentence.startsWith("JavaScript");
console.log(check2); // false

// second argument specifies the starting position
let check3 = sentence.startsWith("JavaScript", 11);
console.log(check3); // true



Recommended Reading: JavaScript String endsWith()