String.endsWith Redirect 1

This is an experimental technology, part of the Harmony (ECMAScript 6) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

Summary

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

Syntax

str.endsWith(searchString [, position]);

Parameters

searchString
The characters to be searched for at the end of this string.
position
Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.

Description

This method lets you determine whether or not a string ends with another string.

Examples

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Polyfill

This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.endsWith with the following snippet:

if (!String.prototype.endsWith) {
    Object.defineProperty(String.prototype, 'endsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function (searchString, position) {
            position = position || this.length;
            position = position - searchString.length;
            var lastIndex = this.lastIndexOf(searchString);
            return lastIndex !== -1 && lastIndex === position;
        }
    });
}

Specifications

Specification Status Comment
ECMAScript Language Specification 6th Edition (ECMA-262) Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support Not supported 17 (17) Not supported Not supported Not supported
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support Not supported Not supported 17.0 (17) Not supported Not supported Not supported

See also

Document Tags and Contributors

Contributors to this page: Sheppy
Last updated by: Sheppy,
Hide Sidebar