Let’s assume we have a secret passcode
'bacon' and want to check if it exists in another string.
Here we’ll use
findme to demonstrate the string we want to check:
const passcode = 'bacon'; const findme = `8sowl0xebaconxjwo98w`;
Visually we can see that
We can introduce a new feature in ES6, the
String.prototype.includes method, which will return us a Boolean value based on whether the substring was found:
const found = findme.includes(passcode); // true console.log(found);
🐛 Check the browser support for String includes! Either compile your code with Babel or provide a polyfill.
This is a really nice method and it gives us a straight-up Boolean answer - but it wasn’t always this way.
String.prototype.indexOf - where we can ask for the index of the start of the string, should it match. If it does match, we get the index, or we get
-1, so naturally our safety check does exactly this:
const index = findme.indexOf(passcode); // true console.log(index !== -1);
-1 isn’t the best looking code, it feels a bit archaic - so prefer the use of
String.prototype.includes where appropriate.
You could also use the bitwise operator
~ instead as a little shorthand, and we’ll leave it at that:
const index = !!~findme.indexOf(passcode); // true console.log(index);
!!~ converts the resulting bitwise expression to a Boolean. It’s basically a fancy way of forcing
indexOf to return us
false in one line.
We’ve covered the new ES6
String.prototype.includes method and compared it to the previously-favoured
The different between the two is
includes will return you a Boolean and
indexOf will return you a number.
includes is the go-to method unless you need to know the index!
🕵️♀️ Learn more about the indexOf method for finding a string inside a string
🎉 Download it free!
Ready to go beyond ForEach? Get confident with advanced methods - Reduce, Find, Filter, Every, Some and Map.
- 31 pages of deep-dive syntax, real-world examples, tips and tricks
- Write cleaner and better-structured programming logic within 3 hours
✅ Success! Check your email, enjoy.
As an extra bonus, we'll also send you some extra goodies across a few extra emails.