In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript.
The endsWith method is used to find out if a string ends with the character or substring you pass as a parameter to the method. The endsWith method works with any type of string. It is accepted by standard strings declared with single or double quotes, as well as by String objects or literal templates.
The endsWith method will return true if the string begins with the given substring or false otherwise:
const achain = 'a chain';
achain.endsWith('ain'); // true
achain.endsWith('Hello');// false
The endsWith method also accepts a second optional parameter that allows the length of the string to be delimited to the specified character when checking. The character is specified by its numeric position, starting at position1:
const achain = 'a chain';
achain.endsWith('ch', 4); // true
achain.endsWith('ch', 5); // false
In the following example we use an object of type string, which behaves in exactly the same way:
const achain = new String('a chain');
achain.endsWith('ch', 4); // true
achain.endsWith('ch', 5); // false