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

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

Example

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

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

console.log(res);

The code execution result:

javascripttrue

Example

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

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

console.log(res);

The code execution result:

javascriptfalse

Example

Let's start checking from a given position:

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

console.log(res);

The code execution result:

javascripttrue

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