JavaScriptStrings

String.prototype.endsWith()

Checks whether a string ends with the given text. Returns true or false.

Returns
true if the string ends with the given text, false otherwise.
Changes the original
No
On this page

Example

#
JavaScript
const file = 'avatar.png'

console.log(file.endsWith('.png'))
console.log(file.endsWith('.jpg'))
console.log(file.endsWith('.PNG'))
Console
true
false
false

Definition and usage

#

The endsWith() method compares the end of a string with the given piece of text. It returns true when the text ends exactly as given, with letter case taken into account.

Typical uses include checking a file extension (.png, .pdf), the domain in an email address, or the tail end of an identifier. The method accepts plain text, and a regular expression throws a TypeError.

The optional second argument, endPosition, makes the method treat the string as if it ended at that position. That lets you check whether a piece of text ends at a specific spot.

Syntax

#
Syntax
string.endsWith(searchString)
string.endsWith(searchString, endPosition)

Parameters

#
  • searchString

    string

    The text the string should end with.
  • endPosition

    number, optional

    The position treated as the end of the string. Defaults to string.length.

More examples

#
Filtering files by extension
JavaScript
const files = ['index.html', 'style.css', 'app.js', 'logo.SVG', 'utils.js']

const scripts = files.filter((name) => name.endsWith('.js'))
const images = files.filter((name) => name.toLowerCase().endsWith('.svg'))

console.log(scripts)
console.log(images)
Console
['app.js', 'utils.js']
['logo.SVG']
Using endPosition
JavaScript
const sentence = 'Code HTML and CSS'

console.log(sentence.endsWith('HTML', 9))
console.log(sentence.endsWith('CSS'))
Console
true
true

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • File extensions are sometimes written in uppercase, such as .JPG. Lowercase the name before checking it.
  • Don't treat a file extension as a security measure. A file named report.exe.png ends with .png, but its actual contents could be something else entirely.

Related entries

#

Spotted a mistake or missing an example? Write to us.