How to Check If a String Contains Another Substring in JavaScript

In JavaScript, strings are often used to manipulate text. A common operation is checking if a string contains another substring.

There are several ways to check if a string contains a substring in JavaScript, and in this Javascript tutorial, we’ll discuss some of the most common methods.


Using the indexOf() Method

The indexOf() method is the most straightforward way to check if a string contains a substring.

This method returns the index of the first occurrence of the substring, or -1 if it does not exist.

let str = "Hello, World!";
let substring = "Hello";

console.log(str.indexOf(substring) !== -1); // true

Using the includes() Method

The includes() method is another way to check if a string contains a substring.

This method returns a boolean value of true if the substring is present, and false otherwise.

let str = "Hello, World!";
let substring = "Hello";

console.log(str.includes(substring)); // true

Using the search() Method

The search() method is similar to the indexOf() method, but it returns the index of the first occurrence of the substring, or -1 if it does not exist.

let str = "Hello, World!";
let substring = "Hello";

console.log(str.search(substring) !== -1); // true

Using the match() Method:

The match() method is used to search for a match between a regular expression and a string.

To check if a string contains a substring, you can use the regular expression with the ‘test’ method.

let str = "Hello, World!";
let substring = "Hello";

console.log(new RegExp(substring).test(str)); // true

Conclusion

In conclusion, there are several ways to check if a string contains a substring in JavaScript.

You can use the indexOf() method, the includes() method, the search() method, or the match() method with the ‘test’ method.

Choose the method that best fits your use case and make sure to test your code thoroughly before deploying it to production.

I hope this tutorial helped you understand how to check if a string contains another substring in JavaScript.

If you have any questions or comments, feel free to leave them below.