endsWith() Method for JavaScript: Checking String Endings
In JavaScript, determining whether a string ends with a particular character is a common need. While a variety of approaches exist, the most efficient and cross-browser compatible method is to utilize the endsWith() function.
Built-in endsWith() Method
Unfortunately, as of the writing of the original post in 2010, JavaScript did not have a native endsWith() method. However, since ECMA6, this functionality has been added to the core language. To use it, simply call endsWith() on the string object, passing in the character or substring you want to check for:
const str = "mystring#"; console.log(str.endsWith("#")); // Output: true
Custom Implementation
If you are unable to use the native endsWith() method, a custom implementation can be created:
String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; };
This function uses the indexOf() method to search for the suffix in the string, starting from a position that skips the last suffix.length characters. If the suffix is found at the end, the return value will be greater than or equal to 0, indicating that the string ends with the specified character.
Other Approaches
Other less efficient methods include:
In conclusion, the native endsWith() method is the preferred way to check if a string ends with a particular character in JavaScript. For older browser compatibility, a custom implementation can be used.
The above is the detailed content of How to Check if a JavaScript String Ends With a Specific Character?. For more information, please follow other related articles on the PHP Chinese website!