JavaScript string includes(): Check if a string contains the specified string

The JavaScript includes() method is used when we need to check whether a string contains a specified substring or not. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "codescracker.com";

      if(myString.includes("cracker"))
         document.getElementById("xyz").innerHTML = "'cracker' is in the string";
      else
         document.getElementById("xyz").innerHTML = "'cracker' is not in the string";
   </script>
   
</body>
</html>
Output

JavaScript includes() syntax

The syntax of the includes() method in JavaScript is:

string.includes(substring, startIndex)

The startIndex parameter is optional. Its default value is 0.

The includes() method returns true if the specified substring is in the string. Otherwise, it returns false.

JavaScript includes() example

Consider the following code as an example demonstrating the "includes()" method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>

   <script>
      let mystr = "JavaScript is Fun. Is not it?";
      document.getElementById("abc").innerHTML = mystr.includes("Fun");
   </script>
   
</body>
</html>
Output

Here is another example with the startIndex parameter to includes():

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="myPara"></p>

   <script>
      let mystr = "JavaScript is Fun. Is not it?";
      document.getElementById("myPara").innerHTML = mystr.includes("Fun", 16);
   </script>
   
</body>
</html>
Output

Indexing starts with 0. Therefore, in the string "JavaScript is Fun. Is not it?"

Since 16 is the index number provided as startIndex in the above example. Therefore, the search for Fun in the string JavaScript is Fun. Is not it? starts after "JavaScript is Fun".

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!