How to check if a string includes substring - JS

Mo Ibra

Mo Ibra

Jan 5, 2023

In this article we will learn how to check if a string includes substring in JavaScript.

It is very common to check if a string includes substring in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to check if a string includes substring or not.

Now let's imagine that we have an string like this:

"Hello In JavaScript World!!"

And want to check if this string contains "JavaScript" or not.

How to solve this problem?

Solving this problem is easy, especially because there is a function called includes that does everything for us.

The includes() method returns true if the substring is contained in the string. Otherwise, false is returned.


Check if a string includes substring

As we said before, we can use includes to check if a string contains substring or not.

Let's see an example

// String
const string = "Hello In JavaScript World!!";

// Check
const check = string.includes("JavaScript");

// Result:
console.log(check);

Output

true

And when we know the return value from the method (True or false), we can write lines of code based on that value.

// String
const string = "Hello In JavaScript World!!";

const check = string.includes("JavaScript");

// If `true`
if (check)
{
    console.log('Yay!');
}
// If `false`
else
{
    console.log('Ops!')
}

Output

Yay!

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: