How to Check if a JavaScript String Contains a Substring

You’ll want to know how to checking if a string contains a substring in JavaScript for things like data handling, validation and manipulation in your apps. It lets you perform things ranging from simple searches to complex pattern matching. This guide dives further into these strategies.

How to use the includes method in JavaScript?

The includes() method offers a straightforward approach to determine if a string contains a specific substring. It returns true if it finds the substring, and false otherwise. Remember, this method is case-sensitive.

const string = "Hello, world!"; const substring = "world"; const containsSubstring = string.includes(substring); console.log(containsSubstring); // Output: true

How to use the indexOf method in JavaScript?

Before the advent of includes, developers commonly used indexOf() for substring searches. indexOf() returns the starting index of the substring within the string, or -1 if the string does not contain the substring. A return value greater than -1 indicates the presence of the substring.

const string = "Hello, world!"; const substring = "world"; const containsSubstring = string.indexOf(substring) > -1; console.log(containsSubstring); // Output: true

Performing a case-insensitive search

To ignore case differences between the string and the substring, convert both to the same case using either toLowerCase() or toUpperCase() before performing the search.

const string = "Hello, World!"; const substring = "world"; const containsSubstring = string.toLowerCase().includes(substring.toLowerCase()); console.log(containsSubstring); // Output: true

Using regular expressions for complex searches

For searches that require pattern matching or case insensitivity, regular expressions are highly effective. Use the test method to check if the string matches the pattern defined by the regular expression.

const string = "Hello, world!"; const pattern = /world/i; // 'i' flag for case-insensitive search const containsSubstring = pattern.test(string); console.log(containsSubstring); // Output: true

Invite only

We're building the next generation of data visualization.