69 of 264 menu

startsWith method

The startsWith method checks if a string starts with the substring specified in the first parameter. If it starts, then it returns true, and if it doesn't, then false. The second optional parameter of the method is the position from which to start checking (by default, from the start of the string).

Syntax

string.startsWith(what to search, [where to start checking]);

Example

Let's check if a string starts with a given substring:

let str = 'abcde'; let res = str.startsWith('abc'); console.log(res);

The code execution result:

true

Example

Let's check if a string starts with a given substring:

let str = 'abcde'; let res = str.startsWith('xxx'); console.log(res);

The code execution result:

false

Example

Let's start checking from a given position:

let str = 'abcde'; let res = str.startsWith('bc', 1); console.log(res);

The code execution result:

true

See also

  • the endsWith method
    that checks the end of a string
  • the indexOf method
    that searches for the first occurrence of a substring
  • the includes method
    that searches for a string
  • the at method
    that searches for a string character
enru