The String endsWith() Method: A Comprehensive Guide
Learn all about the endsWith() method in JavaScript strings and its various functionalities.
The endsWith() method in JavaScript allows you to determine whether a string ends with a specified value passed as a parameter.
Here are a couple of examples to understand its usage:
1 | 'JavaScript'.endsWith('Script') // true |
In the first example, the endsWith() method returns true because the string ‘JavaScript’ ends with the value ‘Script’. However, in the second example, the method returns false because it performs a case-sensitive comparison, and the value ‘script’ does not match the string’s ending ‘Script’.
You can also include a second parameter, denoting the length of the substring to be considered for the comparison. If the second parameter is present, the endsWith() method will consider the original string as if it was longer by that many characters.
Let’s look at some examples to clarify:
1 | 'JavaScript'.endsWith('Script', 5) // false |
In the first example, ‘JavaScript’ does not end with ‘Script’ in the first 5 characters. Hence, the method returns false.
However, in the second example, ‘JavaScript’ ends with ‘aS’ within the first 5 characters. Thus, the endsWith() method returns true.
The endsWith() method was introduced as part of ECMAScript 2015, which is also commonly referred to as ES6.
tags: [“JavaScript”, “endsWith()”, “string manipulation”, “ECMAScript”]