The JavaScript string.endsWith() method
The endsWith() method checks whether a string ends with a given substring and returns true or false. "photo.png".endsWith(".png") is true. It's perfect for checking file extensions and suffixes, and it's the mirror of startsWith(). The match is case-sensitive.
Overview
endsWith() tells you whether a string finishes with some text, returning a clean boolean. "report.pdf".endsWith(".pdf") is the textbook use — checking a file's extension without slicing or a regex. It reads exactly like what it does, which makes the intent obvious.
It's the tail-end counterpart to startsWith(): one checks the beginning, the other the end. The match is case-sensitive, so lowercase both sides first if case shouldn't matter — important for extensions, since files can be .PNG or .png.
An optional second argument lets you treat the string as if it ended at a given length, which is occasionally useful for checking a prefix region. For a match anywhere in the string rather than at the end, use includes().
Syntax
str.endsWith(searchString)
str.endsWith(searchString, endPosition)
"photo.png".endsWith(".png") // true
"photo.png".endsWith(".jpg") // false
Parameters
The string.endsWith() method accepts the following parameters.
| Parameter | Description |
|---|---|
searchString |
The text to test for at the end. Case-sensitive. |
endPosition |
Optional. Treat the string as if it ended at this length. Defaults to the full length. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const files = ['logo.PNG', 'data.csv', 'photo.png'];
const images = files.filter(f => f.toLowerCase().endsWith('.png'));
document.getElementById('out').textContent =
'images: ' + images.join(', '); // images: logo.PNG, photo.png
</script>
Best practices
- Use it to check file extensions and suffixes —
name.endsWith(".pdf"). - Lowercase both strings first for a case-insensitive check (extensions vary in case).
- Use startsWith() for the beginning of a string.
- For a match anywhere, not just the end, use includes().
Frequently asked questions
How do I check if a string ends with something?
str.endsWith("suffix"), which returns true or false.How do I check a file extension in JavaScript?
filename.toLowerCase().endsWith(".png") — the lowercasing handles mixed-case extensions.Is endsWith() case-sensitive?
What is the difference between endsWith() and includes()?
endsWith() only matches at the end; includes() matches anywhere in the string.