user
In JavaScript, how to get the length of a string?
alphonsio

The property string.length returns the number of bytes in a string, i.e. the length.

let str ="Hello world";
len = str.length;  // len = 11, the length of str

In JavaScript, you can get the length of a string using the .length property. Here’s how you can do it:

Example:

let myString = "Hello, world!";
let lengthOfString = myString.length;

console.log(lengthOfString); // Outputs: 13

Explanation:

  • The length property returns the number of characters in the string, including spaces and punctuation.
  • You can use it directly on any string variable or string literal.

Warning

string.length returns the number of bytes, not the number of characters. Some characters (UTF-8, UNICODE ...) are encoded on several bytes :

let str ="😀";
console.log (str.length); // Display 2

Additional Note:

The .length property counts all characters, including whitespace, so " " (three spaces) would return a length of 3.