How to check if text is in a string with JavaScript?

Sometimes, we want to check if text is in a string with JavaScript.

In this article, we’ll look at how to check if text is in a string with JavaScript.

How to check if text is in a string with JavaScript?

To check if text is in a string with JavaScript, we can use the JavaScript string’s includes method.

For instance, we write:

const str = "car, bicycle, bus";
const str2 = "car";
console.log(str.includes(str2));

We call str.includes with str2 to check whether the str2 string’s content is in str1.

Therefore, the console log should log true since 'car' is in 'car, bicycle, bus'.

Conclusion

To check if text is in a string with JavaScript, we can use the JavaScript string’s includes method.