Extension and suffix validation
Validate a file or URL suffix before processing it.
JavaScript · Function
Determines whether a string ends with a specified string and returns true or false. An optional end position lets you test a portion of the string.
Call this method on a string to test whether the characters before a chosen endpoint match the supplied search string. The endpoint defaults to the string's length, so the ordinary form checks the actual suffix; the optional endpoint lets you test a prefix of the string as though it ended there.
endsWith(searchString)
endsWith(searchString, endPosition)| Name | Type | Description |
|---|---|---|
searchString | string | The characters to search for at the end of the string; non-regex values are coerced to strings. |
endPosition | number | Optional position where the search string is expected to end; defaults to the string length. |
A boolean: true when the searched characters match at the selected end position, otherwise false.
const filename = "report.final.pdf";
console.log(filename.endsWith(".pdf")); // true
console.log(filename.endsWith(".pdf", 10)); // falseChecks a filename suffix and demonstrates that a shorter end position changes the portion being tested.
Validate a file or URL suffix before processing it.
Check whether user-facing text has a required ending without regular expressions.
Test a string segment ending at a known index.
It returns a boolean indicating whether the string ends with the characters in searchString. The default endpoint is the string length, and an empty search string returns true.
Follow-up: What does the second argument do? It supplies the endpoint used for the comparison, so the method tests the substring ending at that position rather than necessarily the full string.
The first argument is converted to a string unless it is a regular expression. A regular expression causes a TypeError instead of being accepted as a pattern.
Follow-up: Why does a regex throw? The method is designed for string matching, and the API explicitly rejects regex arguments.
endPosition is the position at which the searched text is expected to finish, with a default of str.length. Values outside the string's range are effectively bounded to the valid range.
Follow-up: What happens when the endpoint is too early for the search string? The method returns false because the requested search text cannot fit before that endpoint.
String.prototype.startsWith()String.prototype.includes()String.prototype.indexOf()String.prototype.slice()