Emmanuel Akinfulubi

JavaScriptBasic

startsWith, endsWith and includes in JavaScript

Beginner · 3 min read

Does this phone number start with 080? Does this file name end with .pdf? Does this message mention a refund? Questions like these are everywhere in code, and JavaScript has three string methods that answer them in words you can read out loud: startsWith, endsWith and includes.

In this tutorial you will check a phone number's prefix, its last four digits and a run of digits in the middle. You'll also meet the optional position argument most people don't know about, and see what happens when you pass a regular expression. You need to know what a string is and what true and false are.

Three yes-or-no questions

Each method returns true or false:

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

JavaScript

console.log('report.pdf'.endsWith('.pdf')); // true
console.log('report.pdf'.startsWith('.pdf')); // false

The older way: indexOf

Before these methods existed, people used indexOf, which returns the position where some text is first found, or -1 if it isn't there. "Starts with" became indexOf(x) === 0, and "contains" became indexOf(x) !== -1. It works, but === 0, > 0 and !== -1 all look alike and mean different things. One slip and the check is wrong.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

112 Prefix, suffix and contains

easy

Check whether a phone number starts with 080, ends with the four digits a customer quoted, and contains a run of digits. Use startsWith, endsWith and includes, including their position arguments, and see what happens if you pass a regex.

Stuck? Three hints, smallest first
  1. 1. All three take an optional position: a start offset for two of them, an end offset for endsWith.
  2. 2. The old form is indexOf(needle) === 0.
  3. 3. These three refuse a regular expression outright.

Step 1: prefix, suffix and contains

Step 1

const phone = '08031234567';
console.log(phone.startsWith('080')); // true
console.log(phone.endsWith('4567'));  // true
console.log(phone.includes('123'));   // true

Each line reads like the question it asks. Compare the old spelling of the first one:

JavaScript

const phone = '08031234567';
console.log(phone.indexOf('080') === 0); // true

Same answer, but you have to stop and think about what === 0 means.

Step 2: start somewhere else

startsWith takes a second argument: the position to start checking from. startsWith(x, i) asks "does x appear exactly at position i?":

Step 2

const phone = '08031234567';
console.log(phone.startsWith('803', 1)); // true
console.log(phone.startsWith('803'));    // false

The character at position 0 is the leading zero, so '803' begins at position 1. This is a neat way to check a fixed part of a formatted string, such as the digits after a leading zero, without cutting it out with slice first.

Step 3: pretend the string ends early

endsWith also takes a second argument, but it means something different: the position to treat as the end of the string.

Step 3

const phone = '08031234567';
console.log(phone.endsWith('0803', 4)); // true

endsWith('0803', 4) looks only at the first four characters, '0803', and asks whether that ends with '0803'. It does.

Step 4: upper and lower case

Step 4

console.log('Yaba'.startsWith('yaba'));               // false
console.log('Yaba'.toLowerCase().startsWith('yaba')); // true

All three methods are case sensitive: Y and y are different characters. Lowercase the text first when case shouldn't matter, for example when you're matching what someone typed into a search box.

Step 5: a regular expression is refused

A regular expression is a search pattern written between slashes. You might try one here:

Step 5

const phone = '08031234567';
try {
  phone.startsWith(/^080/);
} catch (err) {
  console.log(err.name); // TypeError
}

Instead of quietly turning the pattern into the text "/^080/" and searching for that, JavaScript throws a TypeError. For a pattern, use the regex's own test method: /^080/.test(phone).

Step 6: the empty string is in everything

Step 6

const phone = '08031234567';
console.log(phone.includes(''));   // true
console.log(phone.startsWith('')); // true

Every string contains the empty string. This matters when the text you search for comes from an empty search box: a filter like items.filter((x) => x.includes(query)) then keeps everything. That's often what you want, but make sure it's on purpose.

The full solution

The answer panel checks the phone number's prefix, suffix and middle, compares the old indexOf form, uses both position arguments, tests case and the empty string, and catches the regex TypeError. It also checks the state code at the start of the plate number KJA-234-XY. Press Run to see the output.

The answer

const phone = '08031234567';
const plate = 'KJA-234-XY';
let regexThrew = '';
try {
  phone.startsWith(/^080/);
} catch (err) {
  regexThrew = err.name;
}
console.log('network prefix:', phone.slice(0, 4), 'starts with 080:', phone.startsWith('080'));
console.log('plate state code:', plate.startsWith('KJA'));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a prefix check reads as English', phone.startsWith('080'), true);
test('a suffix check too', phone.endsWith('4567'), true);
test('and contains, anywhere in the middle', phone.includes('123'), true);
test('the old form was an indexOf comparison', phone.indexOf('080') === 0, true);
test('startsWith takes an offset to start from', phone.startsWith('803', 1), true);
test('endsWith takes the position to treat as the end', phone.endsWith('0803', 4), true);
test('the checks are case sensitive', ['Yaba'.startsWith('yaba'), 'Yaba'.toLowerCase().startsWith('yaba')], [false, true]);
test('a regex argument is refused, not coerced', regexThrew, 'TypeError');
test('every string contains the empty string', [phone.includes(''), plate.startsWith('')], [true, true]);

These three replaced a generation of indexOf comparisons, and the win is that startsWith('080') cannot be typed wrong while indexOf('080') === 0 can: > 0, !== -1 and === 0 mean three different things and look alike at a glance.

The position arguments are the part people miss. startsWith(needle, i) asks whether the needle appears at i, which is a cheap way to test a fixed field inside a formatted string without slicing it out first, and endsWith(needle, i) pretends the string ends at i. Passing a regex throws a TypeError rather than stringifying it, so startsWith(/^080/) fails immediately instead of silently comparing against "/^080/" — for a pattern you want test (exercise 114 does the phone properly). And every string includes '', which matters when the needle comes from an empty search box: the filter matches everything, which is usually what you want, but by accident rather than design.

Common mistakes

  • Mixing up the two position arguments. For startsWith it's where to start; for endsWith it's where the string should be treated as ending.
  • Forgetting case. 'Yaba'.includes('yaba') is false. Lowercase both sides when case doesn't matter.
  • Passing a regex. These methods only take text. Use /pattern/.test(text) for patterns.

Try it yourself

  1. Write isPdf(fileName) that returns true for 'Report.PDF' as well as 'report.pdf'.
  2. Use startsWith with a position to check that 'KJA-234-XY' has a hyphen at position 3.
  3. Filter ['Yaba', 'Ikeja', 'Yaba Tech'] to keep the items that include what's in a query variable. Try query = 'Yaba' and query = ''.

Keep practising

Newsletter

New writing, when it lands.

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