String.prototype.endsWith()
Tests whether a string ends with the given characters, returning true or false.
endsWith(searchString)
endsWith(searchString, endPosition)- Added in JavaScript ECMAScript 2015
Parameters
| Parameter | Type | Description |
|---|---|---|
$searchString | string | The characters expected at the end of the string. Cannot be a regex; all other values are coerced to strings. |
$endPositionoptional | number= str.length | The end position at which searchString is expected to be found — the index of its last character plus 1. The string is treated as if it were only this long. |
Return value
booleantrue if the characters are found at the end of the string (including when searchString is empty); otherwise false.
Errors
Throws a TypeError if searchString is a regular expression.
endsWith() is the suffix counterpart to startsWith() and the readable replacement for str.slice(-suffix.length) === suffix — an idiom that quietly breaks when the suffix is empty, since slice(-0) returns the whole string.
endPosition is exclusive
The second argument is not an index to search from; it is a pretend length. str.endsWith(x, n) asks whether str.slice(0, n) ends with x. So "Cats are best".endsWith("Cats", 4) is true: truncate to the first four characters and the answer is yes. Passing the index of the last character instead of that index plus one is the standard off-by-one here.
Gotchas
- Case-sensitive.
"IMAGE.PNG".endsWith(".png")isfalse; lowercase the filename first. - Regexes throw
TypeError. Use/\.png$/i.test(name)when you want a pattern. - An empty suffix is always true.
- Query strings and fragments defeat it.
"/a/photo.png?v=2"does not end with.png— strip the URL first.
Like every string comparison here, it works on UTF-16 code units, so normalise text that may carry combining accents.
Example
When to use it
- Route a file by extension after lowercasing the name
- Check whether a base URL already carries a trailing slash
- Detect a sentence-ending punctuation mark before appending text
- Test that a generated identifier carries an expected suffix
Frequently asked questions
How do I check a file extension in JavaScript?
Use name.toLowerCase().endsWith(".png") so case does not matter. Strip any query string or fragment first, since "photo.png?v=2" does not end with ".png".
What does the second argument of endsWith() mean?
It is an exclusive end position — the string is treated as if it were only that many characters long. endsWith(x, n) is equivalent to str.slice(0, n).endsWith(x).
Can endsWith() take a regular expression?
No, passing a regex throws a TypeError. Use an anchored pattern such as /\.png$/i.test(name) when you need matching rules rather than a literal suffix.
More examples
Joining URLs without doubling the slash
Each combination of trailing and leading slashes produces exactly one separator. Both checks are needed — testing only one side leaves either a doubled or a missing slash.
const join = (base, path) =>
(base.endsWith("/") ? base.slice(0, -1) : base) +
(path.startsWith("/") ? path : "/" + path);
console.log(join("https://api.test/", "/v1/users")); // https://api.test/v1/users
console.log(join("https://api.test", "v1/users")); // https://api.test/v1/users
console.log(join("https://api.test/", "v1")); // https://api.test/v1Why slice(-n) is not a safe substitute
With a non-empty suffix the two approaches agree. With an empty one, -0 makes slice return the entire string and the comparison fails, while endsWith() correctly reports true.
const suffix = "";
const name = "report.pdf";
console.log(name.slice(-suffix.length) === suffix); // false — slice(-0) is the whole string
console.log(name.endsWith(suffix)); // true — correct answer
console.log(JSON.stringify(name.slice(-0))); // "report.pdf"
console.log(name.endsWith(".pdf"), name.slice(-4) === ".pdf"); // true true
Discussion