Write a JavaScript Program to Check Whether a String Contains a Substring

In JavaScript, you can easily check if a string contains a specific substring by using the includes() method.

This method returns true if the string contains the specified substring, and false otherwise.

Here’s how you can use the includes() method to check if a string contains a substring in JavaScript:

const str = "Hello, world!";
const substr = "world";

if (str.includes(substr)) {
  console.log("The string contains the substring.");
} else {
  console.log("The string does not contain the substring.");
}

In this example, we have a string str and a substring substr. We use the includes() method to check if str contains substr.

If it does, we log a message to the console saying that the string contains the substring. If it doesn’t, we log a message saying that the string does not contain the substring.

It’s important to note that the includes() method is case-sensitive. So if you’re looking for a substring that has a different case than the rest of the string, you may need to convert both the string and the substring to the same case before checking if it contains the substring.

Here’s an example of how to convert both the string and the substring to lowercase before using the includes() method:

const str = "Hello, world!";
const substr = "WORLD";

if (str.toLowerCase().includes(substr.toLowerCase())) {
  console.log("The string contains the substring.");
} else {
  console.log("The string does not contain the substring.");
}

In this example, we convert both the string and the substring to lowercase using the toLowerCase() method before using the includes() method to check if the string contains the substring.

In conclusion, checking if a string contains a substring in JavaScript is easy using the includes() method.

Just make sure to account for case-sensitivity if needed, and you’ll be able to check for substrings in no time!