String.prototype.endsWith()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
El método endsWith()
determina si una cadena de texto termina con los caracteres de una cadena indicada, devolviendo true
o false
según corresponda.
Pruébalo
const str1 = "Cats are the best!";
console.log(str1.endsWith("best!"));
// Expected output: true
console.log(str1.endsWith("best", 17));
// Expected output: true
const str2 = "Is this a question?";
console.log(str2.endsWith("question"));
// Expected output: false
Sintaxis
str.endsWith(searchString[, position])
Parámetros
searchString
-
Los caracteres a buscar hasta el final de la cadena
str
. length
Opcional-
Si se indica, se utiliza como el tamaño de
str
. Por defecto se usastr.length
.
Valor devuelto
true
si los caracteres proporcionados se encuentran al final de la cadena de texto; en caso contrario, false
.
Descripción
Este método determina si una cadena de texto termina en otra cadena o no. Este método distingue entre mayúsculas y minúsculas.
Polyfill
Este método ha sido añadido a la especificación ECMAScript 6 y puede no estar disponible en todas las implementaciones de JavaScript. Sin embargo, puedes implementar el polyfill String.prototype.endsWith()
con el siguiente fragmento de código:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
Ejemplos
Usando endsWith()
let 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
Especificaciones
Specification |
---|
ECMAScript® 2025 Language Specification # sec-string.prototype.endswith |
Compatibilidad con navegadores
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
endsWith |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support