JavaScript String length | Find 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 = "fresherearth";
      document.getElementById("xyz").innerHTML = myString.length;
   </script>
   
</body>
</html>
Output

JavaScript string.length Syntax

The syntax of 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 string.

Find Length of a String entered by User in JavaScript

Let me create an example that allows 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 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:

JavaScript Online Test


« Previous Tutorial Next Tutorial »