The endsWith()
method determines whether a string ends with the characters of another string, returning true
or false
as appropriate.
str.endsWith(searchString[, position])
searchString
position
true
if the string ends with the characters of the search string; otherwise, false
.
This method lets you determine whether or not a string ends with another string. This method is case-sensitive.
endsWith()
var 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
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) { String.prototype.endsWith = function(searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.lastIndexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; }
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'String.prototype.endsWith' in that specification. | Standard | Initial definition. |
ECMAScript 2017 Draft (ECMA-262) The definition of 'String.prototype.endsWith' in that specification. | Draft |
Feature | Chrome | Firefox (Gecko) | Edge | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 41 | 17 (17) | (Yes) | No support | No support | 9 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | No support | 36 | 17.0 (17) | No support | No support | No support |
String.prototype.startsWith()
String.prototype.includes()
String.prototype.indexOf()
String.prototype.lastIndexOf()
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith