JavaScript Code

JavaScript String startsWith()


String startsWith()

In JavaScript, String.startsWith() method is used to check if the string starts with a specific prefix string or search string.

Syntax

str.startsWith(search, start)

where

  • str is a string.
  • search is a string.
  • start is an integer, and optional.

startsWith() method returns true if the string str starts with the specified search string, or else it returns false. If start is provided, only the part of the string str from the specified start index position is considered for checking.

Examples

1. In the following program, we check if string value in name starts with search string 'ap'.

let name = 'apple';
let output = name.startsWith('ap');
console.log(output);

2. In the following program, we check if string value in name starts with search string 'ba'.

let name = 'apple';
let output = name.startsWith('ba');
console.log(output);

3. In the following program, we check if string value in name starts with search string 'pp' with a start index of 1.

let name = 'apple';
let output = name.startsWith('pp', 1);
console.log(output);


Copyright @2022