Subscribe

Vanilla JavaScript string includes

✍️

Lets see how we can determine if a string contains a substring in JavaScript

10 May, 2020 · 2 min read

While we recently checked if a string startsWith or a string endsWith a specific substring, today we will learn how to find out if a string includes another substring.

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

JavaScript includes() function

We can use the includes() function by calling it on a string and passing a substring to it:

const 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

It is important for the includes() function to know that it is a case-sensitive function. So the following code will fail:

const 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

String includes with offset position parameter

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

const 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

See the code examples in this Codepen

Feel free to play with the code here:

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter