In JavaScript, How Can You Determine If A String Contains A Specific Substring?

In JavaScript, you can use the includes() method or the indexOf() method to check whether a string contains a substring.

Method 1: includes()

The includes() method returns true if the string contains the specified substring, or false otherwise.

Here’s an example:

const string = "Hello, world!";
const substring = "Hello";

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

Method 2: indexOf()

The indexOf() method returns the starting index of the first occurrence of the substring within the string. If the substring is not found, it returns -1.

Here’s an example:

const string = "Hello, world!";
const substring = "Hello";

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

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

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!