String.prototype.endsWith
Checks whether a string ends with the given text.
Available since: ES2015
Syntax
str.endsWith(searchString, endPosition)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchString | string | The text the string should end with. |
| endPosition | number | Optional. Treat the string as if it had this length. The whole string by default. |
Return value
booleantrue if the string ends with that text.
Examples
Checking a file extension:
console.log('photo.jpg'.endsWith('.jpg'));
console.log('photo.png'.endsWith('.jpg'));Output:
true
falseCase matters — convert the string to one case first:
const file = 'PHOTO.JPG';
console.log(file.endsWith('.jpg'));
console.log(file.toLowerCase().endsWith('.jpg'));Output:
false
trueNotes
Its pair is startsWith(). Neither method accepts regular expressions.
See also
- String.prototype.startsWith — Checks whether a string starts with a given substring.
- String.prototype.includes — Checks whether a string contains a given substring.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.