Javascript Check if string contains a substring


In this post, we will see how to check if string contains substring

Using IndexOf Method:

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

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

In this example, the indexOf() method returns the position of the first occurrence of the substring within the string, or -1 if it’s not found. So, we are checking if the result of indexOf() is not equal to -1, which means the substring was found.

Using String Includes:

Another alternative is to use the includes() method, which returns a boolean value indicating whether the string contains the specified substring or not:

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

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

Thanks for Reading..