Checking for Substring in Javascript (ES6 Way)

Use-Cases of this Tutorial

  • 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';

	console.log('Substring present');
	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 .

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

var sub = 'are';

// true

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *