--- title: String.prototype.endsWith() slug: Web/JavaScript/Reference/Global_Objects/String/endsWith translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith original_slug: Web/JavaScript/Referencia/Objectes_globals/String/endsWith ---
El mètode endsWith() method determina si un string acaba amb els caràcters d'un altre string, retornant true o false depenent d'això.
str.endsWith(stringAcercar[, posició])
stringAcercarposicióposició com la última posició del string; per defecte rep el valor del tamany total del string.Aquest mètode us permet determinar si un string acaba en un altre string.
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
Aquest mètode va ser afegit a l'especificació ECMAScript i pot no estar disponible encara a totes les implementacions de JavaScript. No obstant, la funció següent emula el comportament de String.prototype.endsWith():
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.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
| Especificació | Estat | Comentaris |
|---|---|---|
| {{SpecName('ES6', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}} | {{Spec2('ES6')}} | Definició inicial. |
| Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Suport bàsic | {{CompatChrome("41")}} | {{CompatGeckoDesktop("17")}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |
| Característica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Suport bàsic | {{CompatNo}} | {{CompatChrome("36")}} | {{CompatGeckoMobile("17")}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |