Home > Web Front-end > JS Tutorial > How Can I Check if a String Ends with a Specific Character in JavaScript?

How Can I Check if a String Ends with a Specific Character in JavaScript?

Barbara Streisand
Release: 2024-11-22 05:31:16
Original
861 people have browsed it

How Can I Check if a String Ends with a Specific Character in JavaScript?

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)
Copy after login

自定义 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;
};
Copy after login

This function operates by:

  • Skipping unnecessary comparisons using indexOf()'s second parameter
  • Allowing seamless usage in Internet Explorer
  • Avoiding regex complexities

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;
}
Copy after login

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;
    };
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template