JavaScript startsWith() | Check if String starts with Substring

The JavaScript startsWith() method is used to check if a specified string starts with specified substring. For example:

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

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

   <script>
      let myString = "JavaScript is Fun. Is not it?";
      
      if(myString.startsWith("JavaScript"))
         document.getElementById("xyz").innerHTML = "The string starts with 'JavaScript'";
      else
         document.getElementById("xyz").innerHTML = "The string does not starts with 'JavaScript'";
   </script>
   
</body>
</html>
Output

JavaScript startsWith() Syntax

The syntax of startsWith() method in JavaScript is:

string.startsWith(substring, startIndex)

The substring argument is required, used to check whether the string starts with substring or not.

The startIndex argument is optional. The default value of this argument is 0.

The startsWith() method returns true if specified string starts with specified substring. Otherwise returns false. For example:

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

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

   <script>
      let myString = "JavaScript is Fun. Is not it?";
      document.getElementById("xyz").innerHTML = myString.startsWith("Python");
   </script>
   
</body>
</html>
Output

Only use the startIndex argument if you want to apply the index number from where you need to check whether the string starting from that index starts with specified substring or not. For example:

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

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

   <script>
      let myString = "JavaScript is Fun. Is not it?";
      document.getElementById("xyz").innerHTML = myString.startsWith("Is", 19);
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »