Skip to content

String.prototype.endsWith(): check a suffix (ES2015)

  • What String.prototype.endsWith() returns and how endPosition differs from the position argument of startsWith.
  • Why the pre-ES2015 slice(-n) and lastIndexOf workarounds 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.

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.

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 ES2015
console.log(file.indexOf(suffix, file.length - suffix.length) !== -1); // true
console.log(file.lastIndexOf(suffix) === file.length - suffix.length); // true
console.log(file.slice(-suffix.length) === suffix); // true
// ES2015
console.log(file.endsWith('.pdf')); // true
console.log(file.endsWith('ORD-1042', 16)); // true: treat the string as if it were 16 characters long

The indexOf form is correct but hard to read; the other two break at the edges.

// Fragment: signature
str.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); // false
console.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 === -1
console.log(s.endsWith(longer)); // false
console.log('report.csv'.endsWith('report', 6)); // true: only the first 6 characters count
console.log('report.csv'.endsWith('.csv', 100)); // true: endPosition is clamped to the length
console.log('report.csv'.endsWith('r', 0)); // false: nothing before index 0
console.log('report.CSV'.endsWith('.csv')); // false: case-sensitive

Output:

false
true
true
false
true
true
false
false

The 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.

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 true
photo.jpeg true
label.pdf.exe false
notes.txt false
pdf false
ana@example.test true true
mallory@badexample.test true false
Lee@EXAMPLE.test false true

Including 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.

  • Suffix without its separator. email.endsWith('example.test') accepts badexample.test; name.endsWith('pdf') accepts pdf and notpdf. 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.PDF fails a .pdf check unless you lowercase first.
  • Expecting subdomains to match. '@example.test' does not match ana@mail.example.test. Decide whether subdomains are allowed, parse the domain after the last @, and compare explicitly.
  • Multi-part extensions. archive.tar.gz ends with .gz, not .tar.gz, unless you check the longer suffix first.
  • Hand-rolled slice(-n) or lastIndexOf checks. They fail for an empty suffix (-0 is 0) or a suffix one character too long. Use endsWith.
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

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.

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.

  • endsWith (ES2015) compares the code units that end at endPosition (default: the length) with the search string.
  • It removes the off-by-one and empty-suffix bugs of the slice and indexOf workarounds.
  • 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.