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 = "codescracker.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 the above example:

javascript endswith

In this example, the value "codescracker.com" is assigned to the myString variable, and the value "com" is assigned to the mySubString variable. The endsWith() method is then used to determine whether myString ends with the substring "com". If the condition is met, the console will display "The string ends with com"; otherwise, it will display "The string does not end with com."

Because the condition in this example is true, the console will display "The string ends with com."

In the above example, the endsWith() method is used to check if the given string myString ends with the substring mySubString.

JavaScript endsWith() syntax

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

string.endsWith(subString, length)

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

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

Check if a string ends with a specified value in JavaScript

The following HTML and JavaScript code checks if a specified value is available at the end of a string.

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, true is the output that is produced in the above example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!