Using String endsWith() method to coding in Javascript/JS

This JavaScript tutorial explains how to use the string approach known as endsWith() with syntax and examples.

Description

In JavaScript, endsWith() is a string method that is used to decide whether a string ends with a specific sequence of characters. Because the endsWith() technique is a technique of the String object, it ought to be invoked via a specific occasion 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 quit of string. length Optional. It is the size 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 authentic if the substring is found at the cease of string. Otherwise, it returns false.

Note

The endsWith() technique performs a case-sensitive search. The endsWith() technique does no longer trade the price 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 cost of ‘TechOnTheNet’. We have then invoked the endsWith() technique of the totn_string variable to seem to be for a precise set of characters at the quit of totn_string.

We have written the output of the endsWith() approach to the net browser console log, for demonstration purposes, to exhibit what the endsWith() approach returns.

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

true
false

As you can see, the endsWith() technique back actual for the first call, but false for the second call. Because the endsWith() approach performs a case-sensitive search, the substring ‘Net’ is observed at the end of the string ‘TechOnTheNet’ but ‘net’ is now not found.

Specifying a Length Parameter

Next, let’s see what happens if you specify a size 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 net browser console log:

true

In this example, we have set the length parameter to a fee of 6. This ability that solely the first 6 characters of the string will tested. So in this case, the substring ‘On’ is determined at the quit of the string ‘TechOn’ (which is the first 6 characters of the totn_string variable).