Description

JavaScript string method endsWith() returns true if a string ends with the specified string; else returns false.

Syntax

Here is the basic syntax, where str is a string.

str.endsWith(searchString, length)

Parameters

The method accepts the below parameters.

searchString

  • String to be searched for at the end of str
  • If the index cannot be converted to an integer or is not provided, then the default value 0 is used.

length (optional)

  • Optional parameter
  • Length of the str within which the method will search for searchString. Default value is str.length.

Result

The method returns true if the string str contains the searchString at the end of the str. Otherwise returns false.

Example 1: Using the method

For a valid integer index value, the method returns the character from the specified index.

var str = "Learning JavaScript is fun";

// Checking if the string ends with "fun"
document.write(str.endsWith("fun"));        // Prints: true

// Checking if the string ends with "is"
document.write(str.endsWith("is"));         // Prints: false

Output:

true
false

Example 2: The method is case-sensitive

The method endsWith() is case-sensitive, so it treats fun and Fun as two different strings.

var str = "Learning JavaScript is fun";

// Checking if the string ends with "fun"
document.write(str.endsWith("fun"));        // Prints: true

// Checking if the string ends with "Fun"
document.write(str.endsWith("Fun"));        // Prints: false

Output:

true
false

Example 3: Using method with both parameters

The parameter length is used to specify the length (from the beginning) of the string str to consider while checking for searchString.

var str = "Learning JavaScript is fun";

// Checking if the string ends with "is"
document.write(str.endsWith("is", 22));        // Prints: true

// Checking if the string ends with "is"
document.write(str.endsWith("is", 10));        // Prints: false

Output:

true
false

Overall

JavaScript string method endsWith() returns true if a string ends with the specified string; else returns false.

Related Links