Skip to main content

Command Palette

Search for a command to run...

Searching strings in JavaScript

Updated
1 min read
Searching strings in JavaScript

Everyone loves a good ol' regex, but sometimes it's a bit overkill when you simply want to check for the presence of a basic string inside another. Recently, I learned that JavaScript provides three helpful methods that may remove the need to go for regex.

  • endsWith()

  • includes()

  • startsWith()

const firstName = "John";
const emailAddress = "john.doe@example.com";

console.log(emailAddress.startsWith(firstName.toLowerCase())); // true
console.log(emailAddress.includes("@")); // true
console.log(emailAddress.endsWith("gmail.com")); // false

Each of the three methods also accepts a second optional parameter that specifies an offset.

const fullName = "John Doe";

console.log(fullName.startsWith("John")); // true
console.log(fullName.startsWith("John", 4)); // false

Disclaimer: Each of these methods is case-sensitive. If you need case insensitivity, I'd recommend either regex or applying .toLowerCase() on both strings - just ensure you're doing it in an immutable fashion.

More from this blog

Today I Learned

15 posts