String. prototype. endsWith()
Checks whether a string ends with the given text. Returns true or false.
- Returns
trueif the string ends with the given text,falseotherwise.- Changes the original
- No
Example
#const file = 'avatar.png'
console.log(file.endsWith('.png'))
console.log(file.endsWith('.jpg'))
console.log(file.endsWith('.PNG'))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
#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 tostring.length.
More examples
#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)const sentence = 'Code HTML and CSS'
console.log(sentence.endsWith('HTML', 9))
console.log(sentence.endsWith('CSS'))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.pngends with.png, but its actual contents could be something else entirely.
Related entries
#- String.prototype.startsWith()Checks whether a string starts with the given text. Returns true or false.
- String.prototype.includes()Checks whether a string contains the given piece of text. Returns true or false, and is case-sensitive.
- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- String.prototype.toLowerCase()Returns a copy of the string converted to lowercase. Useful for comparisons and normalizing data.
Spotted a mistake or missing an example? Write to us.