Does JavaScript Support EndsWith Method?
In JavaScript, determining whether a string ends with a specific character can be achieved through various methods. While a dedicated endsWith() method was not natively available in earlier versions, modern browsers and ES6 provide this functionality.
原生 endsWith() 方法 (ES6)
ES6 introduced the endsWith() method, which directly checks the end of a string for a specified suffix. Its syntax is:
string.endsWith(suffix, length)
自定义 endsWith() 函数
Before ES6, developers used custom functions to emulate endsWith(). The most efficient approach, as outlined in the provided answer, is:
String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; };
This function operates by:
Stand-alone endsWith() Function
If modifying native prototypes is undesirable, a stand-alone function can be used:
function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }
Checking for Native Implementation
To ensure compatibility with browsers that may not have native endsWith(), a simple check before defining the custom function is recommended:
if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; }
Conclusion:
Depending on the JavaScript version and browser compatibility requirements, the choice between using the native endsWith() method or a custom implementation varies. For modern browsers and ES6 support, the native endsWith() offers a straightforward and efficient solution.
The above is the detailed content of How Can I Check if a String Ends with a Specific Character in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!