Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
true

Ignoring 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
true

One 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:

true

Common 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:

true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.