Vanilla JavaScript string includes
permalinkWhile 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 permalink
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 permalink
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 permalink
Feel free to play with the code here:
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