user
How to get the length of a string in JS?
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.

Disclaimer

This chatbot (Alphonsio) provides automated responses generated by machine-learning algorithms and relies on the accuracy of the underlying language models. While this Chatbot is programmed to provide accurate and relevant information, its information may not always be exhaustive, accurate, up-to-date or tailored to individual circumstances. It is not a substitute for professional advice or consultation with qualified experts. This chatbots and its responses are intended for informational purposes only and should not be used for commercial or business purposes. The creators of this chatbot are not liable for any damages or losses incurred as a result of using the information provided. By using our website, you acknowledge and agree to these terms. The data you submit to this chatbot is used to improve our algorithms. Under no circumstances should you submit sensitive data such as, but not limited to, personal data or passwords. The data you submit could then be made public.