How to Find the Length of a String in JavaScript

← PrevNext →

You can use the “length” property in JavaScript, to find the length of a string or an object. I’ll show you how.

image
Find the length of a string in JavaScript

Syntax of “length” property

String.length

It’s a built-in property and it returns the length a given string. It counts number of characters, including spaces, and returns a number.

It also counts the spaces (blank spaces) in between the string or anything inside the opening and closing quotes (Note: You can use single or double quotes).

Let's find the Length of a String

<body>
    <p id='p1'></p>
</body> 

<script>	
    let my_intro = new String('Hi, my name is Arun Banik and welcome to my blog.');

    document.getElementById('p1').innerHTML = 'The string: ' + my_intro;
    document.getElementById('p1').innerHTML = 
        document.getElementById('p1').innerHTML + 
            '<br /> The length of the string: <b>' + my_intro.length + '</b>';
</script>
Try it
The output of the above example is 49. There are 49 characters total, including the spaces in between the single quotes (you can use double quotes also).
If the string has more spaces, it will count it too. For example,

let my_intro = new String('Hi, my name is Arun Banik and welcome to my blog.');

The length of the above string is now 52. Since, I have added two spaces after the word is.

Now let’s try with special characters. A string can be anything.

<script>	
    let str = new String('1 % 5 =');
    document.write (str.length);
</script>
Try it

The output would be 7.

Length of Empty string

If a string is empty, the length property would return a zero. For example,

let str = new String('');
document.write (str.length);

Get the length of a String in a Variable

In the above examples, I have used the String() function to define a string value and then get the length. However, if you are storing data in a variable, you can still use the length property with a variable to get the length of the string. For example,

<script>	
    let str;        
    str = 'Hello, Welcome to my blog :-)';
    document.write (str.length);
</script>
Try it

Or, using a const …

<script>
const str = 'Hello, Welcome to my blog :-)';
document.write (str.length);
</script>

Remember, a string is any text or data that is stored within a single quote or a double quote. The length property works with a string and the string can be used with a String() method or a variable.

Thanks for reading .

← PreviousNext →