Comprehensive Guide to JavaScript String endsWith Method: From Manual Implementation to Native Support

Nov 17, 2025 · Programming · 12 views · 7.8

Keywords: JavaScript | String_Processing | endsWith_Method | ES6 | Compatibility

Abstract: This article provides an in-depth exploration of various methods for checking string endings in JavaScript, focusing on the ES6-introduced native endsWith() method and its working principles. It compares manual implementation approaches with native methods in terms of performance, covers cross-browser compatibility handling, parameter usage techniques, and practical application scenarios. Through complete code examples and performance analysis, developers can master best practices for string ending detection.

Introduction

In JavaScript development, checking whether a string ends with specific characters or substrings is a fundamental yet crucial string operation requirement. This article systematically introduces multiple approaches to implement this functionality in JavaScript, ranging from early manual implementations to modern native support.

Manual Implementation Methods

Before the ES6 standard was released, JavaScript lacked a built-in endsWith method, requiring developers to implement it manually. Based on the best answer from the Q&A data, we can adopt the following efficient implementation:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

This implementation offers several advantages: First, it avoids the overhead of creating substrings by directly using the native indexOf method for searching; Second, it skips unnecessary comparisons by specifying the search starting position through the second parameter; Finally, it maintains good cross-browser compatibility, including support for Internet Explorer.

For developers who prefer not to modify native object prototypes, an independent function version is also available:

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

ES6 Native endsWith Method

With the release of the ECMAScript 6 (ES6) standard, JavaScript formally introduced the String.prototype.endsWith() method. According to the reference article, the basic syntax of this method is as follows:

str.endsWith(searchString)
str.endsWith(searchString, endPosition)

The searchString parameter specifies the string to search for, while endPosition is an optional parameter that specifies the ending position for the search. The method returns a boolean value indicating whether the string ends with the specified string.

Practical usage examples:

const str = "To be, or not to be, that is the question.";
console.log(str.endsWith("question.")); // true
console.log(str.endsWith("to be")); // false
console.log(str.endsWith("to be", 19)); // true

Performance Analysis and Comparison

Modern JavaScript engines have heavily optimized string operations. According to performance test results from the Q&A data, a simple implementation using the substr method performs well in modern browsers:

this.substr(-suffix.length) === suffix

This implementation approach shows the fastest speed in Chrome, comparable performance to the indexOf method in IE11, and only minor performance differences in Firefox. When the result is false, this implementation performs better across all browsers.

Compatibility Handling

To ensure code runs correctly in older browser versions, it's recommended to add type checking to avoid overwriting existing implementations:

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

This approach ensures backward compatibility while not affecting the performance of native methods in modern browsers.

Parameter Characteristics and Considerations

The endsWith method has several important characteristics regarding parameter handling: The searchString parameter cannot be a regular expression, and all non-regex values are coerced to strings. If this parameter is omitted or undefined is passed, the method searches for the string "undefined", which is typically not the desired behavior.

The endPosition parameter specifies the ending position for the search, with the default value being the string length. This feature allows the method to check whether any position in the string ends with the specified string, providing greater flexibility.

Practical Application Scenarios

The endsWith method has widespread applications in web development, including: file extension checking, URL path validation, data format verification, etc. For example, checking image file extensions:

function isImageFile(filename) {
    return filename.endsWith(".jpg") || 
           filename.endsWith(".png") || 
           filename.endsWith(".gif");
}

Conclusion

Methods for checking string endings in JavaScript have evolved from manual implementations to native support. In modern development, the ES6 endsWith method should be prioritized, while compatibility requirements should be considered. Understanding the performance characteristics and applicable scenarios of different implementation approaches helps in writing efficient and robust code.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.