How to Check Whether a String Contains a Substring in JavaScript

As a software developer, checking if a string contains a substring is a common task.

In JavaScript, there are several ways to achieve this.

In this article, we’ll explore various methods to check if a string contains a substring in JavaScript.


Method 1: Using the includes() method

The simplest and most straightforward way to check if a string contains a substring is to use the includes() method.

The includes() method returns a Boolean value indicating whether the string contains the substring.

Example:

let string = "Hello World";
let substring = "Hello";

console.log(string.includes(substring)); // returns true

Method 2: Using the indexOf() method

The indexOf() method returns the index of the first occurrence of the substring in the string.

If the substring is not present, the method returns -1. We can use this information to check if the string contains the substring.

Example:

let string = "Hello World";
let substring = "Hello";

if (string.indexOf(substring) !== -1) {
console.log("Substring is present");
} else {
console.log("Substring is not present");
}

Method 3: Using the search() method

The search() method is similar to the indexOf() method, but it also accepts regular expressions as an argument.

Example:

let string = "Hello World";
let substring = "Hello";

if (string.search(substring) !== -1) {
console.log("Substring is present");
} else {
console.log("Substring is not present");
}

Method 4: Using the RegExp() object

We can also use the RegExp() object to check if a string contains a substring.

The RegExp() object is used to create a regular expression pattern.

We can then use the test() method to check if the string contains the substring.

Example:

let string = "Hello World";
let substring = "Hello";

let regex = new RegExp(substring);

if (regex.test(string)) {
console.log("Substring is present");
} else {
console.log("Substring is not present");
}

Conclusion

In this blog post, we explored various methods to check if a string contains a substring in JavaScript.

From the simple includes() method to the more complex RegExp() object, each method has its own advantages and disadvantages.

Choose the method that best fits your needs and use it to check if a string contains a substring in JavaScript.