In this video, we will learn when and how to use
includes() method on Strings.
string.includes() method determine whether or not a string includes another string.
let message = 'Hi guys! meet Shayne, he is our hero!'console.log(message.includes('Shayne'));console.log(message.includes(‘Shayne' , 40));console.log(message.includes('!'));
00:47 It takes two arguments and returns true or false based on if that specific value was included. The first argument is the search string we are looking for. And the second is an optional position argument, which indicates the index to begin the search from. Calling message dot includes with a single argument, Shayne returns true because message indeed contains the string. Shayne. Here is another usage that takes position argument and we are passing 40 which means we want to start searching for the word Shayne starting from that index. Since there is no occurrence of string, Shayne, it returned false. Now let's try out some examples for includes method in the editor. So here we are. We have the message. "Hi guys, meet Shayne, he is our hero".Now our goal is to find a Shayne word exist in this message. So let's write console log message dot includes if this message includes the word Shayne.
01:42 and if we run it, it should return true. And there you go! What if we want to give the position argument as well? Let's try another thing. Console dot log.
02:01 message dot includes() Shayne with position 40 now we want to find if message includes the word Shayne starting from position 40 and position is nothing but the index. Let's try to run it and see and it returns false. And that is because Shayne exists way before index 40 how can we check that? Let's check the length of the string.
02:31 Now length is a property of string. It's not a method. So we never call it with the parentheses. We only call the methods with parentheses and pass in the arguments needed. And let's add another argument length to the console.log() so that we know we are displaying the length of the string. And now when we run it, the length of the entire string message is 37 and we are trying to find the word Shayne starting from index 40 it's going to return false anyway. Includes method doesn't just find out if the word exists, but it also works on the characters. So if we want to find out of message contains the character !, We write message.includes(''!") And it should return true. But we want to run and see what happens and it returns true. And this pretty much gives you an idea how to use includes method in the strings. Thanks for watching. I'll be covering more videos on strings, so be sure to subscribe and until then, keep learning and share your knowledge.