Vanilla JavaScript string includes

— 3 minute read

While we recently checked if a string startsWith or a string endsWith a specific substring. We are now going to find out if a string contains another substring.

To do so, we are using the JavaScript function includes().

Using includes() function in JavaScript permalink

We can use this function by calling it on a string and passing a substring to it.

var string =
'The greatest glory in living lies not in never falling, but in rising every time we fall.';

// Check if it includes with `living`
console.log(string.includes('living'));
// true

For the includes() function it is important to know it's a case sensitive function, so the following will fail:

var string =
'The greatest glory in living lies not in never falling, but in rising every time we fall.';

// Check if it includes with `Living`
console.log(string.includes('Living'));
// false

Using an offset starting position with includes() permalink

As the brothers startsWith() and endsWith() this one has another position parameter. This position is from where it will start to look.

var string =
'The greatest glory in living lies not in never falling, but in rising every time we fall.';

// Check if it includes with `living`
console.log(string.includes('living', 30));
// false

Feel free to play with this Codepen:

See the Pen Vanilla JavaScript string includes by Chris Bongers (@rebelchris) on CodePen.

Browser Support permalink

This function works well in all modern browsers, including edge!

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter