endsWith method

The endsWith method checks if a string ends with the substring specified in the first parameter. If it ends, then it returns true, and if it doesn't, then false. The second optional parameter can specify the string length. In this case, the check will not be the real end of the string, but the specified.

Syntax

javascriptstring.endsWith(what to search, [string length]);

Example

We check if a string ends with a given substring:

javascriptlet str = 'abcde';
let res = str.endsWith('cde');

console.log(res);

The code execution result:

javascripttrue

Example

We check if a string ends with a given substring:

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

console.log(res);

The code execution result:

javascriptfalse

Example

Let's set the length of the string to be checked:

javascriptlet str = 'abcde';
let res = str.endsWith('bc', 3);

console.log(res);

The code execution result:

javascripttrue

See also

  • the startsWith method
    that checks the start of a string
  • the indexOf method
    that searches for the first occurrence of a substring
  • the lastIndexOf method
    that searches for the last occurrence of a substring
  • the includes method
    that searches for a string
  • the at method
    that searches for a string character