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ò.
Sintaxi
str.endsWith(stringAcercar[, posició])
Paràmetres
stringAcercar
- Els caràcters a cercar al final d'aquest string.
posició
- Opcional. Cerca dins aquest string considerant
posició
com la última posició del string; per defecte rep el valor del tamany total del string.
Descripció
Aquest mètode us permet determinar si un string acaba en un altre string.
Exemples
Utilitzar 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
Polyfill
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;
};
}
Especificacions
Especificació | Estat | Comentaris |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'String.prototype.endsWith' in that specification. |
Standard | Definició inicial. |
Compatibilitat amb navegadors
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Suport bàsic | 41 | 17 (17) | No support | No support | No support |
Característica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Suport bàsic | No support | 36 | 17.0 (17) | No support | No support | No support |