Checking for Substring in Javascript

Use-Cases of this Tutorial

  • You are looking to find whether a string contains a specific substring or not.

ES6 has introduced a new and better way to check for a substring in a given string — the includes() method. It returns a true if the substring is present and false otherwise.

// given string
var main = 'animals are a treat to watch';

// substring to check
var sub = 'animals';

if(main.includes(sub)) 
	console.log('Substring present');
else
	console.log('Substring not present');

The includes() method also accepts a second parameter that sets the position where to start searching for the substring. If not passed it is default set to 0.

var main = 'animals are a treat to watch';

var sub = 'are';

// true
console.log(main.includes(sub));

// true
console.log(main.includes(sub, 5));

// false
console.log(main.includes(sub, 15));