How to check if a string starts or ends with a substring
Short answer
The startsWith() method checks the beginning of a string, endsWith() checks the end:
const file = 'report-2025.pdf';
console.log(file.startsWith('report'));
console.log(file.endsWith('.pdf'));Output:
true
trueIgnoring case
Both methods are case-sensitive. Convert the string to lowercase first:
const file = 'PHOTO.JPG';
console.log(file.endsWith('.jpg'));
console.log(file.toLowerCase().endsWith('.jpg'));Output:
false
trueOne of several variants
To check several prefixes at once, combine some() with startsWith():
const url = 'https://example.com';
const secure = ['https://', 'wss://'].some((prefix) => url.startsWith(prefix));
console.log(secure);Output:
trueCommon mistake
Comparing with indexOf(...) === 0 also works, but it searches the whole string and reads worse. Also note that an empty substring always matches:
console.log('hello'.startsWith(''));Output:
trueFunctions used in this recipe
- String.prototype.startsWith — Checks whether a string starts with a given substring.
- String.prototype.endsWith — Checks whether a string ends with the given text.
- String.prototype.toLowerCase — Converts a string to lowercase.