Esta página ha sido traducida del inglés por la comunidad.Aprende más y únete a la comunidad de MDN Web Docs.
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 septiembre de 2015.
El métodoendsWith() determina si una cadena de texto termina con los caracteres de una cadena indicada, devolviendotrue ofalse según corresponda.
In this article
Pruébalo
const str1 = "Cats are the best!";console.log(str1.endsWith("best!"));// Expected output: trueconsole.log(str1.endsWith("best", 17));// Expected output: trueconst str2 = "Is this a question?";console.log(str2.endsWith("question"));// Expected output: falseSintaxis
str.endsWith(searchString[, position])
Parámetros
searchStringLos caracteres a buscar hasta el final de la cadena
str.lengthOpcionalSi 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 polyfillString.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
>UsandoendsWith()
let str = "To be, or not to be, that is the question.";console.log(str.endsWith("question.")); // trueconsole.log(str.endsWith("to be")); // falseconsole.log(str.endsWith("to be", 19)); // trueEspecificaciones
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.endswith> |