To determine if a string ends with a specific substring in JavaScript, there are several methods available. The most straightforward approach is to use the built-in `String.prototype.endsWith()` method, which provides a clean and efficient way to perform this check. Below, I will outline the method, provide practical examples, discuss best practices, and highlight common mistakes developers might encounter.
The `endsWith()` method is part of the ECMAScript 6 (ES6) specification and allows you to check if a string ends with a given substring. It returns a boolean value: `true` if the string ends with the specified substring, and `false` otherwise.
string.endsWith(searchString[, length])
The `length` parameter is optional and allows you to specify a length of the string to consider. If omitted, the entire string is used.
const str = "Hello, world!";
console.log(str.endsWith("world!")); // true
console.log(str.endsWith("Hello")); // false
console.log(str.endsWith("world", 12)); // true
While `endsWith()` is the most modern and recommended approach, there are alternative methods for older browsers or specific use cases.
You can manually check if a string ends with a substring by using the `substring()` method combined with the `length` property:
const str = "Hello, world!";
const substring = "world!";
const result = str.substring(str.length - substring.length) === substring;
console.log(result); // true
Another method is to use regular expressions, which can be more powerful but also more complex:
const str = "Hello, world!";
const regex = /world!$/;
console.log(regex.test(str)); // true
In conclusion, checking if a string ends with a substring can be efficiently achieved using the `endsWith()` method, with alternative methods available for specific scenarios. By following best practices and being aware of common pitfalls, developers can ensure robust and error-free string manipulations in their applications.