How to Check If a String Contains a Substring in JavaScript

To check if a string contains substring in JavaScript, you can use the “String.prototype.includes()”, “String.prototype.indexOf()”, or “String.prototype.search()” method.

Method 1: Using String.prototype.includes()

The most straightforward and recommended way to check whether the string contains a substring is to use the String.prototype.includes() function. Introduced in ES6, the includes() method checks if a string contains a specified substring and returns a boolean value (true if found, false if not).

Example

const str = "Harry, Potter!";
const substring = "Potter";

const containsSubstring = str.includes(substring);
console.log(containsSubstring);

Output

true

Method 2: Using String.prototype.indexOf()

The indexOf() is a built-in string method that returns the index of the first occurrence of the specified substring in the string or -1 if the substring is not found. You can use this method to check for the presence of a substring by comparing the result against -1.

Example

const str = "Harry, Potter!";
const substring = "Potter";

const containsSubstring = str.indexOf(substring) !== -1;
console.log(containsSubstring);

Output

true

Method 3: Using String.prototype.search()

The search() is a built-in method that takes a regular expression as its argument and returns the index of the first match or -1 if there’s no match. This method is useful when searching for a pattern instead of a specific substring.

Example

const str = "Harry, Potter!";
const substring = "Potter";

const containsSubstring = str.search(new RegExp(substring, 'i')) !== -1;
console.log(containsSubstring);

Output

true

Among these methods, includes() is the most efficient method to check if a string contains a substring, while indexOf() and search() can be helpful in specific scenarios or when working with older JavaScript environments that do not support includes().

Leave a Comment