Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check whether a string ends with some other string - JavaScript
In JavaScript, there are multiple ways to check if a string ends with another string. The most straightforward approach is using the built-in endsWith() method, though you can also implement custom solutions.
Using String.endsWith() (Recommended)
The endsWith() method is the standard way to check if a string ends with a specific substring:
const str1 = 'this is just an example';
const str2 = 'ample';
console.log(str1.endsWith(str2)); // true
console.log(str1.endsWith('temple')); // false
console.log(str1.endsWith('example')); // true
true false true
Custom Implementation Using substr()
You can create a custom function that extracts the ending portion of the string and compares it:
const str1 = 'this is just an example';
const str2 = 'ample';
const endsWith = (str1, str2) => {
const { length } = str2;
const { length: l } = str1;
const sub = str1.substr(l - length, length);
return sub === str2;
};
console.log(endsWith(str1, 'temple')); // false
console.log(endsWith(str1, str2)); // true
false true
Using slice() Method
Another approach uses slice() to extract the ending characters:
const checkEndsWith = (str1, str2) => {
return str1.slice(-str2.length) === str2;
};
const str1 = 'this is just an example';
console.log(checkEndsWith(str1, 'ample')); // true
console.log(checkEndsWith(str1, 'example')); // true
console.log(checkEndsWith(str1, 'test')); // false
true true false
Comparison of Methods
| Method | Performance | Browser Support | Readability |
|---|---|---|---|
endsWith() |
Best | ES6+ (widely supported) | Excellent |
substr() |
Good | All browsers | Good |
slice() |
Good | All browsers | Very good |
Conclusion
Use String.endsWith() for modern applications as it's the most readable and efficient method. For legacy browser support, the slice() approach offers a clean alternative to custom implementations.
Advertisements
