JavaScript String length: Find the Length of a String

The JavaScript length property is used when we need to find the length of a string. For example:

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

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

   <script>
      let myString = "codescracker";
      document.getElementById("xyz").innerHTML = myString.length;
   </script>
   
</body>
</html>
Output

JavaScript string.length syntax

The syntax of the string.length property in JavaScript is:

string.length

where string refers to the string whose length we need to calculate. And length is the property that is used to find the length of a string.

Find the length of a string entered by the user in JavaScript

Let me create an example that allows the user to enter any string to find its length. That is, the example given below produces an output that allows you to enter a string. After entering the string, click on the Find Length button to get the length of the entered string:

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

   <script>
      function myFun()
      {
         let x, len, temp;
         x = document.getElementById("str").value;
         len = x.length;
         temp = document.getElementById("resPara");
         temp.style.display = "block";
         document.getElementById("res").innerHTML = len;
      }
   </script>

   <p>Enter a String: <input id="str"><BR>
   <button onclick="myFun()">Find Length</button></p>
   <p id="resPara" style="display: none;">
   Length of Given String is: <span id="res"></span></p>
   
</body>
</html>
Output

Enter a String:

The function myFun() is invoked when a user enters a string into the input field with the id "str" and clicks the "Find Length" button. The function's job is to get the input value using "document.getElementById("str").value" and then calculate the length. After determining the length, it first makes the hidden paragraph with the id "resPara" visible before writing the length value to the span with the id "res".

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!