How to check if a string ends with another string in JavaScript
Checking if strings end with specific suffixes is essential for file extension validation, URL path checking, data format detection, and implementing features like file type filtering or domain validation in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented suffix checking extensively in components like file upload systems, URL validators, and content processors where determining string endings is crucial for proper data handling and user experience.
From my extensive expertise, the most modern and straightforward solution is using the ES6 endsWith()
method, which provides a clear boolean result.
This approach is intuitive, performant, and specifically designed for suffix detection with excellent readability.
Use the endsWith()
method to check if a string concludes with a specific substring.
const filename = 'document.pdf'
const isPdf = filename.endsWith('.pdf')
// Result: true
The endsWith()
method checks if the string concludes with the specified substring and returns true
if it does, or false
otherwise. In this example, 'document.pdf'.endsWith('.pdf')
returns true
because the string indeed ends with ‘.pdf’. The method is case-sensitive, so filename.endsWith('.PDF')
would return false
unless the original string also uses uppercase. You can optionally specify a length parameter to check only part of the string: filename.endsWith('ment', 8)
checks if the first 8 characters end with ‘ment’.
Best Practice Note:
This is the same approach we use in CoreUI components for file type validation, URL suffix checking, and implementing format-based filtering throughout our component ecosystem.
For case-insensitive checking, convert both strings to lowercase first: text.toLowerCase().endsWith(suffix.toLowerCase())
. For older browser support, use the alternative: text.lastIndexOf(suffix) === text.length - suffix.length
. The endsWith()
method is supported in all modern browsers and provides cleaner syntax than manual substring comparisons.