Javascript String startsWith()

The startsWith() method returns true if a string begins with specified character(s). If not, it returns false.

Example

const message = "JavaScript is fun";

// check if message starts with Java let result = message.startsWith("Java");
console.log(result); // true
// check if message starts with Script result = message.startsWith("Script");
console.log(result); // false

startsWith() Syntax

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.

startsWith() Return Value

  • 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

Output

true
true
false
true

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges