JavaScript includes() | Check if a String contains specified String

The JavaScript includes() method is used when we need to check whether a string contains 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 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 specified substring is in the string. Otherwise returns false.

JavaScript includes() Example

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 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 string "JavaScript is Fun. Is not it?"

  • 'J' is at index no.0
  • 'a' is at index no.1
  • 'v' is at index no.2
  • and so on

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

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋