The String endsWith() method

By

Learn how the JavaScript endsWith() method checks whether a string ends with a given value, plus how a second argument lets you treat it as a shorter string.

~~~

endsWith() checks if a string ends with the value of the string passed as parameter. It returns true or false:

'JavaScript'.endsWith('Script') //true
'JavaScript'.endsWith('script') //false

Notice the second example. The check is case sensitive, so script is not the same as Script.

If case doesn’t matter to you, lowercase the string first with toLowerCase(), then run the check. That’s the usual trick when handling file names coming from users, where .PDF and .pdf should count as the same thing.

A typical use case is checking a file extension:

const file = 'invoice.pdf'

if (file.endsWith('.pdf')) {
  //handle the PDF
}

Before this method existed we did the same check with indexOf() math or a regular expression. endsWith() says exactly what it means, and whoever reads the code understands it at a glance.

The second parameter

You can pass a second parameter with an integer value and (if present) endsWith() will consider the original string as if it was long that many characters:

'JavaScript'.endsWith('Script', 5) //false
'JavaScript'.endsWith('aS', 5) //true

In this example the string is treated as if it were just 'JavaS', its first 5 characters. 'JavaS' does not end with 'Script', but it does end with 'aS'.

It’s a way to check a portion of the string without creating a new one with slice().

Watch out: no regular expressions

You can’t pass a regular expression as the value to search. This doesn’t fail quietly, it throws:

'invoice.pdf'.endsWith(/pdf/)
//TypeError: First argument to String.prototype.endsWith
//must not be a regular expression

The language designers did this on purpose, to keep the door open for future extensions. If you need pattern matching, use a regular expression with its test() method:

/\.pdf$/.test('invoice.pdf') //true

For a plain string check, though, stick with endsWith(). It’s easier to read and you can’t get the escaping wrong.

endsWith() was introduced in ECMAScript 2015, together with its siblings startsWith() and includes(). It’s available in every modern browser and in Node.js, so you can use it without worrying about support.

~~~

Related posts about js: