What is the String endsWith() method in JavaScript?

Overview

The String endsWith() method in JavaScript is used to check whether a string ends with a specified string.

Syntax

The endsWith() method can be declared as shown in the code snippet below:


str.endsWith(str2, len)

Parameter

  • str: The string which is to be checked if its ends with str2.

  • str2: The string to be searched at the end of str.

  • len: The number of characters of str to be searched. It is optional.


If the value of str is not provided, its default value is used. The default value of len is equal to the length of str.

Return value

The endsWith() method returns boolean such that:

  • The return value is true if str ends with str2.

  • The return value is false if str does not end with str2.

Browser compatibility

The endsWith() method is supported by the following browsers:

  • Chrome 41
  • Edge 12
  • Firefox 17
  • Opera 28
  • Safari 9

Code

Consider the code snippet below, which demonstrates the use of the endsWith() method:

let str = 'This is Educative. This is endsWith() example code.'
console.log(str.endsWith('code.'))
console.log(str.endsWith('code.', 10))
console.log(str.endsWith('example.'))

Explanation

A string str is declared in line 1.

  • The endsWith() method is used in line 3 to check is str ends with the string 'code.'. The endsWith() method returns true.

  • The endsWith() method is used in line 4 to check is str ends with the string 'code.'.

    The parameter len passed to the endsWith() method is 10. This means that only first 10 characters of str will be searched to find the string 'code' at the end.

    The endsWith() method returns false. This is because the end of first 10 characters of str is not equal to the string code.

  • The endsWith() method is used in line 5 to check is str ends with the string 'example.'. The endsWith() method returns false.