Check a String Sontains a Substring in JavaScript? [Two Methods]

To check if a string contains a specific substring in JavaScript, you can use the includes() method or the indexOf() method. Here’s how you can use each method:

Using includes() method:

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

if (str.includes(substring)) {
  console.log("Substring found!");
} else {
  console.log("Substring not found.");
}

In this example, the includes() method is used to check if the str string contains the substring. If the substring is found within the string, it returns true, and you can execute the desired code. Otherwise, if the substring is not found, it returns false.

Using indexOf() method:

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

if (str.indexOf(substring) !== -1) {
  console.log("Substring found!");
} else {
  console.log("Substring not found.");
}

In this example, the indexOf() method is used to find the starting index of the substring within the str string. If the substring is found, it returns the starting index (greater than or equal to 0). If the substring is not found, it returns -1. So, by checking if the indexOf() result is not equal to -1, you can determine if the substring exists in the string.

Both includes() and indexOf() methods are case-sensitive. If you want to perform a case-insensitive search, you can convert both the main string and the substring to lowercase or uppercase using methods like toLowerCase() or toUpperCase() before comparing them.

Choose the method that best suits your needs based on your specific use case.