Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.endsWith()

Reference for JavaScript String.prototype.endsWith(): test whether a string ends with given text, use the optional end position, and avoid regex arguments.

The endsWith() method checks whether a string finishes with the characters of another string. It returns true or false, so it fits directly into an if condition.

It is the readable replacement for slicing the end of a string and comparing it by hand. A typical use is checking a file extension or a URL suffix.

JavaScript
"report.pdf".endsWith(".pdf"); // true

Try it

JS Checking suffixes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Filtering by extension

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.endsWith(searchString)
string.endsWith(searchString, endPosition)
Name Description
searchString The text to look for at the end. It is converted to a string. A regular expression is rejected.
endPosition Optional. The index just after the last character to consider, as if the string were only that long. Defaults to the string length. Values are clamped between 0 and the length.

Return value: true if the string (cut at endPosition) ends with searchString, otherwise false.

Exceptions: a TypeError if searchString is a regular expression.

Usage notes

  • The comparison is case-sensitive. Convert both sides with toLowerCase() when case should not matter.
  • An empty search string always returns true, for any string and any endPosition.
  • endPosition shortens the string, it does not move a start. "report.pdf".endsWith("report", 6) asks whether the first six characters end with report.
  • Regular expressions throw. If you need a pattern, use /pattern$/.test(string) with test(). The check exists so that a regex is never silently turned into a literal string.
  • Non-strings are converted: "v2".endsWith(2) is true.
  • It works on UTF-16 code units, like other string methods, so a search string that starts with the second half of an emoji could match in the middle of a pair.
  • Related methods: startsWith() tests the beginning, and includes() tests anywhere.

Browser support

endsWith() is part of ES2015 and works in all current browsers.