How to Calculate String Length in JavaScript

Calculating a string’s length in JavaScript, for beginners. Everything you need to know (and nothing you don’t).

Published Categorized as JavaScript, Web & Code

Suppose you’ve stored the following string in a variable called myString:

let myString = "The quick brown fox jumps over the lazy dog.";

Now let’s suppose that, for one reason or another, you need to calculate the length of this string. What’s the best way to do that?

To calculate the length of a string in characters in JavaScript, reference that string’s length property.

As explained in the MDN Web Docs, length is a read-only property that contains the length of the string in UTF-16 code units.

To reference it, use the following syntax:

String.length

And don’t forget to replace String with the name of your constant or variable!

Building on our example above, here’s how we would reference the length property of the myString variable:

let myString = "The quick brown fox jumps over the lazy dog.";
console.log("This string is " + myString.length + " characters long.");

Fire up your browser’s developer console and give this JavaScript code snippet a spin right now. Or, in case you’re reading this post from your phone or tablet, take a look at the screenshot from mine below:

For an empty string, the length property is 0.

The maximum length of a string, per the specifications for the JavaScript scripting language, 253 – 1 elements (the limit for precise integers). But a string this long would need 16,384 terabytes of storage. So don’t worry about longer texts.

Up next: You should know that the length property counts everything in your string. If your string contains special characters, such as new lines/line breaks, they are included in the count. See our tutorial to learn how to remove them.

By Dim Nikov

Content creator with marketing and web development skills to pay the bills.

Leave a comment

Your email address will not be published. Required fields are marked *