JavaScript startsWith(): Check if the string starts with a substring

The JavaScript startsWith() method is used to check if a specified string starts with a 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 the startsWith() method in JavaScript is:

string.startsWith(substring, startIndex)

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

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

The startsWith() method returns true if the specified string starts with a specified substring. Otherwise, it 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 a 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 »


Liked this post? Share it!