by Sai gowtham

How to check if string contains a substring in JavaScript

We can use includes() method to check if a string contains a substring in JavaScript.

let string = "how are you";
let substring = "you";

console.log(string.includes(substring)); // true

The includes() method returns true if a string is found; else it returns false.

Using indexOf method

Similarly, we can also use the indexOf() method where it returns -1 if a string doesn’t contain a substring else it returns the index of the substring.

Example:

let string = "how are you";
let substring = "you";

console.log(string.indexOf(substring) !== -1); // true
console.log(string.indexOf('fun') !== -1); // false

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course