totn JavaScript

JavaScript: String endsWith() method

This JavaScript tutorial explains how to use the string method called endsWith() with syntax and examples.

Description

In JavaScript, endsWith() is a string method that is used to determine whether a string ends with a specific sequence of characters. Because the endsWith() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the endsWith() method is:

string.endsWith(substring [, length]);

Parameters or Arguments

substring
It is the set of characters that will be searched for at the end of string.
length
Optional. It is the length of string that will be searched. If this parameter is not provided, the endsWith() method will search the full length of the string.

Returns

The endsWith() method returns true if the substring is found at the end of string. Otherwise, it returns false.

Note

  • The endsWith() method performs a case-sensitive search.
  • The endsWith() method does not change the value of the original string.

Example

Let's take a look at an example of how to use the endsWith() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.endsWith('Net'));
console.log(totn_string.endsWith('net'));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the endsWith() method of the totn_string variable to look for a specific set of characters at the end of totn_string.

We have written the output of the endsWith() method to the web browser console log, for demonstration purposes, to show what the endsWith() method returns.

The following will be output to the web browser console log:

true
false

As you can see, the endsWith() method returned true for the first call, but false for the second call. Because the endsWith() method performs a case-sensitive search, the substring 'Net' is found at the end of the string 'TechOnTheNet' but 'net' is not found.

Specifying a Length Parameter

Next, let's see what happens if you specify a length parameter with the endsWith() method.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.endsWith('On',6));

The following will be output to the web browser console log:

true

In this example, we have set the length parameter to a value of 6. This means that only the first 6 characters of the string will tested. So in this case, the substring 'On' is found at the end of the string 'TechOn' (which is the first 6 characters of the totn_string variable).