JavaScript endsWith() | Check if a String ends with a Substring

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

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

   <script>
      let myString = "jobails.com";
      let mySubString = "com";

      if(myString.endsWith(mySubString))
         console.log("The string ends with", mySubString);
      else
         console.log("The string does not ends with", mySubString);
   </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by above example:

javascript endswith

JavaScript endsWith() Syntax

The syntax of endsWith() method in JavaScript is:

string.endsWith(subString, length)

The length parameter is optional. Its default value is the length of string.

The endsWith() method returns true if ends with specified subString, otherwise returns false.

Check if a String ends with Specified Value in JavaScript

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

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

   <script>
      let myStr = "JavaScript is Fun";
      document.getElementById("xyz").innerHTML = myStr.endsWith("Fun");
   </script>
   
</body>
</html>
Output

Since the string myStr contains Fun as its last value, therefore true is the output that is produced in above example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »