Emmanuel Akinfulubi

JavaScriptString

Check a file extension with endsWith in JavaScript

Beginner · 4 min read

Is this upload a PDF? Does this link start with https? Does this file name mention 2025? Questions like these only need a yes or a no, and JavaScript has three methods made exactly for them: includes, startsWith and endsWith.

In this tutorial you will ask all three questions about a file name, 'invoice-2025-04.pdf', without working out a single index. Then you will hand one of them a regular expression and see it refuse. You only need to know what a string is and that true and false are values in JavaScript.

Three yes-or-no questions

Each method returns true or false:

  • text.includes(x): is x anywhere in text?
  • text.startsWith(x): does text begin with x?
  • text.endsWith(x): does text finish with x?

Before these existed, people wrote text.indexOf(x) !== -1. That works, but it asks "where is it?" when you only wanted "is it there?". The new methods read like the question itself.

Here are the positions of our file name, which you will need in one step:

Positions

invoice-2025-04.pdf
        ^      ^
        8      15

Position 8 is where the year starts, and position 15 is the dot.

Here is the exercise. Have a go on your own first, or read on and we will build it together.

9 Does it contain, start with, end with?

easy

Answer three yes-or-no questions about a filename without touching an index. Then hand one of them a regular expression and see what happens.

Stuck? Three hints, smallest first
  1. 1. includes, startsWith and endsWith all return a boolean.
  2. 2. startsWith takes a position; endsWith takes a length to pretend the string stops at.
  3. 3. All three refuse a regular expression, and they refuse it loudly.

Step 1: ask the three questions

Step 1

const file = 'invoice-2025-04.pdf';
console.log(file.includes('2025'));      // true
console.log(file.startsWith('invoice')); // true
console.log(file.endsWith('.pdf'));      // true
console.log(file.includes('2024'));      // false

No positions and no -1. Each line reads like the question it answers.

Step 2: watch the case

All three compare characters exactly, so upper and lower case are different.

Step 2

const file = 'invoice-2025-04.pdf';
console.log(file.endsWith('.PDF'));               // false
console.log(file.toLowerCase().endsWith('.pdf')); // true

People upload REPORT.PDF as often as report.pdf. Lower-case the name first when case shouldn't matter, as the second line does.

Step 3: startsWith with a position

startsWith takes an optional second number: the position to check from. That lets you check the middle of a string.

Step 3

const file = 'invoice-2025-04.pdf';
console.log(file.startsWith('2025', 8)); // true

'invoice-' is 8 characters long, so the year starts at position 8. This asks "starting at position 8, does the text begin with '2025'?".

Step 4: endsWith with a length

endsWith also takes a second number, but it means something else: pretend the string is only this long.

Step 4

const file = 'invoice-2025-04.pdf';
console.log(file.endsWith('04', 15)); // true

The first 15 characters are 'invoice-2025-04', and that piece does end with '04'. So you can check what comes just before the extension without cutting the string yourself.

Step 5: the empty string

Step 5

const file = 'invoice-2025-04.pdf';
console.log(file.includes(''));   // true
console.log(file.startsWith('')); // true

An empty string fits anywhere, so the answer is always true. If the text you search for comes from a search box, check that it isn't empty first.

Step 6: try a regular expression

A regular expression is a pattern for matching text, written between slashes, like /2025/. You might expect includes to accept one. It doesn't.

Step 6

const file = 'invoice-2025-04.pdf';
const withRegex = (() => {
  try {
    return file.includes(/2025/);
  } catch (e) {
    return e.constructor.name;
  }
})();
console.log(withRegex); // 'TypeError'

The full message is First argument to String.prototype.includes must not be a regular expression. startsWith and endsWith refuse in the same way.

The try { } catch (e) { } part runs the code in try, and if it throws an error, runs catch with the error in e. e.constructor.name is the name of the error's type. The (() => { ... })() wrapper is a function that is defined and called straight away, so withRegex holds whatever it returns.

Refusing loudly is the helpful choice here. If includes turned /2025/ into the text '/2025/' and searched for that, you would get a quiet false and a confusing bug.

Step 7: use test for patterns

When you really do need a pattern, ask the pattern instead:

Step 7

const file = 'invoice-2025-04.pdf';
console.log(/2025/.test(file));      // true
console.log(/[0-9]{4}/.test(file));  // true

test is a method on the regular expression. [0-9]{4} means "four digits in a row", something includes could never ask.

The full solution

Here is the complete answer: the three questions, the position and length versions, and the refused regular expression. Press Run to see each answer.

The answer

const file = 'invoice-2025-04.pdf';

// includes, startsWith and endsWith all reject a RegExp argument outright,
// rather than converting it to a string and searching for "/2025/".
const withRegex = (() => {
  try { return file.includes(/2025/); } catch (e) { return e.constructor.name; }
})();

console.log('includes("2025")        :', file.includes('2025'));
console.log('startsWith("invoice")   :', file.startsWith('invoice'));
console.log('endsWith(".pdf")        :', file.endsWith('.pdf'));
console.log('startsWith("2025", 8)   :', file.startsWith('2025', 8), '<- checks mid-string');
console.log('includes(/2025/)        :', withRegex);

Output


      
10 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('includes answers without any index arithmetic', file.includes('2025'), true);
test('and says no for something absent', file.includes('2024'), false);
test('startsWith checks the front', file.startsWith('invoice'), true);
test('endsWith checks the back', file.endsWith('.pdf'), true);
test('startsWith takes a position, so it can check mid-string', file.startsWith('2025', 8), true);
test('endsWith takes a length, treating the string as if it stopped there', file.endsWith('04', 15), true);
test('all three are case sensitive', file.endsWith('.PDF'), false);
test('an empty needle is always included', file.includes(''), true);
test('a regular expression is REFUSED, not stringified', withRegex, 'TypeError');
test('use search or test for a pattern instead', /2025/.test(file), true);

These three exist so that indexOf(x) !== -1 can stop being written. They read as the question you were asking.

The refusal of a RegExp is deliberate and useful: the specification checks for one and throws, rather than converting it to the string '/2025/' and quietly reporting no match. That is a rare piece of the language choosing to fail loudly, and it saves a genuinely confusing afternoon.

Common mistakes

  • Checking .pdf without lower-casing. 'REPORT.PDF'.endsWith('.pdf') is false. Lower-case the name first.
  • Passing a regular expression to includes. It throws a TypeError. Use pattern.test(text).
  • Using includes('pdf') to check an extension. 'pdfguide.txt' includes 'pdf' too. Use endsWith('.pdf'), with the dot.

Try it yourself

  1. Write isImage(name) that returns true for names ending in .jpg, .png or .gif, in any case.
  2. Write isSecureLink(url) that checks the link starts with 'https://'.
  3. Use endsWith with a length to check that 'report-final.pdf' has 'final' just before the extension.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.