DEV Community

Cover image for Vanilla JavaScript string includes
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript string includes

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

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Using an offset starting position with includes()

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
Enter fullscreen mode Exit fullscreen mode

Feel free to play with this Codepen:

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

Browser Support

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

Thank you for reading, and let's connect!

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

Oldest comments (0)