How to Get Number of Characters in a String in Javascript

In this tutorial, you will learn how to get number of characters in a string in javascript. The number of characters in a string represents the length of that particular string including the special characters.

In the following example, we have one input element.  We will simply enter any random string in it and upon click of a button, we will get its length and display that on the screen.  Please have a look over the code example and steps given below.    

HTML & CSS

  • We have 4 elements in the HTML file (div, input, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Get” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <input type="text">
        <button>Get</button>
        <h1>Result</h1>
    </div>
    
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

input, button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected the button, input, and h1 elements using the document.querySelector() method and stored them in btnGet, input, and result variables respectively.
  • We have attached the click event listener to the button element.
  • Inside the event handler function, we are getting string entered in the input element using its value property and getting the total number of characters in a string using its length property.
let btnGet = document.querySelector('button');
let input = document.querySelector('input');
let result = document.querySelector('h1');

btnGet.addEventListener('click', () => {
    result.innerText = input.value.length;
});