--- title: String.prototype.endsWith() slug: Web/JavaScript/Reference/Global_Objects/String/endsWith tags: - JavaScript - Méthode - Prototype - Reference - String - polyfill translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith original_slug: Web/JavaScript/Reference/Objets_globaux/String/endsWith ---
La méthode endsWith() renvoie un booléen indiquant si la chaine de caractères se termine par la chaine de caractères fournie en argument.
str.endsWith(chaîneRecherchée[, position]);
chaîneRecherchéeposition {{optional_inline}}chaîneRecherchée. Si la valeur fournie est supérieure à la longueur de la chaine de caractères, elle ne sera pas prise en compte.true si la chaîne de caractères se termine par la sous-chaîne indiquée, false sinon.
Cette méthode permet de savoir si une chaine de caractères se termine avec une certaine chaine de caractères (comme les autres méthodes fonctionnant avec des chaînes de caractères, cette méthode est sensible à la casse).
var str = "Être, ou ne pas être : telle est la question.";
console.log(str.endsWith("question.")); // true
console.log(str.endsWith("pas être")); // false
console.log(str.endsWith("pas être", 20)); // true
Cette méthode a été ajoutée dans la spécification ECMAScript 6 et peut ne pas être disponible dans toutes les implémentations de JavaScript. Cependant, il est possible d'émuler le comportement de String.prototype.endsWith avec le fragment de code suivant :
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;
};
}
| Spécification | État | Commentaires |
|---|---|---|
| {{SpecName('ES6', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}} | {{Spec2('ES6')}} | Définition initiale. |
| {{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.String.endsWith")}}