String.prototype.endsWith(): check a suffix (ES2015)
What you’ll learn
Section titled “What you’ll learn”- What
String.prototype.endsWith()returns and howendPositiondiffers from thepositionargument ofstartsWith. - Why the pre-ES2015
slice(-n)andlastIndexOfworkarounds give wrong answers in edge cases. - How to check file extensions and email domains without the classic look-alike bugs.
- What a suffix check can and cannot prove about an uploaded file.
Summary
Section titled “Summary”TL;DR: str.endsWith(searchString, endPosition) returns true if the characters of str that end at endPosition (default: the string’s length) are exactly searchString. It is case-sensitive and compares UTF-16 code units.
It was added in ECMAScript 2015 (ES6) and works in every current browser and server runtime (see Compatibility). For prefixes, see startsWith(); the coercion and RegExp rules are the same, so this page focuses on what is specific to suffixes.
The problem it solves
Section titled “The problem it solves”OrdersPortal accepts receipts and photos with return requests. Before ES2015, checking an extension meant computing offsets by hand:
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.
const file = 'invoice-ORD-1042.pdf';const suffix = '.pdf';
// Before ES2015console.log(file.indexOf(suffix, file.length - suffix.length) !== -1); // trueconsole.log(file.lastIndexOf(suffix) === file.length - suffix.length); // trueconsole.log(file.slice(-suffix.length) === suffix); // true
// ES2015console.log(file.endsWith('.pdf')); // trueconsole.log(file.endsWith('ORD-1042', 16)); // true: treat the string as if it were 16 characters longThe indexOf form is correct but hard to read; the other two break at the edges.
How it works
Section titled “How it works”// Fragment: signaturestr.endsWith(searchString)str.endsWith(searchString, endPosition)endPosition is the index just after the last character to compare: the method behaves as if the string were cut to that length. It is converted to an integer and clamped between 0 and the length; if omitted, it is the length. Following the specification, an empty searchString returns true, and if the suffix is longer than the first endPosition characters the result is false. Like startsWith, it throws a TypeError for a RegExp argument and for a null or undefined this.
// The slice(-n) workaround breaks for an empty suffix: slice(-0) is slice(0).const empty = '';console.log('report.csv'.slice(-empty.length) === empty); // falseconsole.log('report.csv'.endsWith(empty)); // true
// The lastIndexOf workaround breaks when the suffix is one character longer than the string.const s = 'ab';const longer = 'xab';console.log(s.lastIndexOf(longer) === s.length - longer.length); // true (wrong): -1 === -1console.log(s.endsWith(longer)); // false
console.log('report.csv'.endsWith('report', 6)); // true: only the first 6 characters countconsole.log('report.csv'.endsWith('.csv', 100)); // true: endPosition is clamped to the lengthconsole.log('report.csv'.endsWith('r', 0)); // false: nothing before index 0console.log('report.CSV'.endsWith('.csv')); // false: case-sensitiveOutput:
falsetruetruefalsetruetruefalsefalseThe lastIndexOf bug is subtle: “not found” is -1, and so is length - suffixLength when the suffix is one character longer than the string, so the comparison succeeds. endsWith has no such arithmetic to get wrong.
Realistic example
Section titled “Realistic example”OrdersPortal runs a first-pass check on uploaded file names and on staff email addresses:
// uploads.mjs - first-pass checks for files attached to OrdersPortal returns.const ALLOWED_EXTENSIONS = ['.pdf', '.png', '.jpg', '.jpeg'];
export function hasAllowedExtension(fileName) { const lower = fileName.toLowerCase(); return ALLOWED_EXTENSIONS.some((ext) => lower.endsWith(ext));}
for (const name of ['receipt.PDF', 'photo.jpeg', 'label.pdf.exe', 'notes.txt', 'pdf']) { console.log(name.padEnd(14), hasAllowedExtension(name));}
// Staff accounts must belong to the example.test domain.const naiveStaff = (email) => email.endsWith('example.test');const staff = (email) => email.toLowerCase().endsWith('@example.test');
for (const email of ['ana@example.test', 'mallory@badexample.test', 'Lee@EXAMPLE.test']) { console.log(email.padEnd(24), naiveStaff(email), staff(email));}Output:
receipt.PDF truephoto.jpeg truelabel.pdf.exe falsenotes.txt falsepdf falseana@example.test true truemallory@badexample.test true falseLee@EXAMPLE.test false trueIncluding the dot (.pdf) rejects a file named just pdf, and including the @ rejects badexample.test. Lowercasing handles receipt.PDF and EXAMPLE.test. Note what the check does not do: a file name is chosen by the user, so .pdf proves nothing about the content. Treat the extension as a usability filter and validate the actual bytes (file signature, MIME sniffing, a parser) on the server.
Common mistakes
Section titled “Common mistakes”- Suffix without its separator.
email.endsWith('example.test')acceptsbadexample.test;name.endsWith('pdf')acceptspdfandnotpdf. Include the@or the.. - Trusting the extension. It is user input. Check the content server-side, and never use the extension alone to decide whether to execute or serve something inline.
- Forgetting case.
receipt.PDFfails a.pdfcheck unless you lowercase first. - Expecting subdomains to match.
'@example.test'does not matchana@mail.example.test. Decide whether subdomains are allowed, parse the domain after the last@, and compare explicitly. - Multi-part extensions.
archive.tar.gzends with.gz, not.tar.gz, unless you check the longer suffix first. - Hand-rolled
slice(-n)orlastIndexOfchecks. They fail for an empty suffix (-0is0) or a suffix one character too long. UseendsWith.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
| Fixed suffix, exact case | str.endsWith(suffix) |
| One of several suffixes | suffixes.some((s) => str.endsWith(s)) |
| Pattern or case-insensitive suffix | /\.(?:pdf|png)$/i.test(str) |
| Suffix of the first n characters | str.endsWith(suffix, n) |
| Prefix | startsWith() |
| Domain of a URL | new URL(str).hostname and compare it |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, String.prototype.endsWith is supported in Chrome 41, Edge 12, Firefox 17, Safari 9 (including iOS), Opera 28, Node.js 4.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it; core-js provides a polyfill.
TypeScript: declared in lib.es2015.core.d.ts as endsWith(searchString: string, endPosition?: number): boolean.
Interview questions
Section titled “Interview questions”1. What is endPosition, and how is it different from startsWith’s position?
endPosition is where the comparison ends (exclusive): the string is treated as if it were that long. startsWith’s position is where the comparison starts. Both are clamped to the string’s bounds.
2. Why is str.slice(-suffix.length) === suffix not a safe replacement?
For an empty suffix, slice(-0) is slice(0), which returns the whole string, so the comparison is false where endsWith('') is true. It also allocates a new string on every call.
3. Senior scenario: OrdersPortal must accept only PDF and image uploads. A teammate proposes name.endsWith('.pdf') || name.endsWith('.png') on the client. Is that enough?
No. It is fine as a quick client-side hint (add lowercasing and the full allowed list), but the server must enforce the rule: check the size, read the file signature or parse the file, store it with a server-generated name and a content type you set, and serve it with Content-Disposition: attachment or from a separate origin. The extension check only improves the user experience.
Key takeaways
Section titled “Key takeaways”endsWith(ES2015) compares the code units that end atendPosition(default: the length) with the search string.- It removes the off-by-one and empty-suffix bugs of the
sliceandindexOfworkarounds. - Include the separator (
.pdf,@example.test) and lowercase both sides for user-facing names. - A suffix proves nothing about file content or URL structure; validate those separately.
Related pages
Section titled “Related pages”- String.prototype.startsWith(): the prefix counterpart.
- String.prototype.includes(): substring anywhere in the string.
- String.prototype.padEnd(): add characters to the end of a string.
- Regular expressions: anchored patterns with
$. - Strings: string basics.
- JavaScript interview questions