
In JavaScript, strings are a common data type used to represent textual data. As with any programming language, it’s important to be able to manipulate and analyze strings. One common task when working with strings is to determine their length. In this blog post, we will explain how to get it in JavaScript.
How to get length of string in JavaScript?
The best way to do this is using length
property that is build in a string prototype object (which means it is available by default):
const message = "Hello world!";
console.log(message.length); // Output will be 12
JavaScript is using UTF-16 code units, which means that the characters in a string are encoded into 16-bit long binary numbers. When length
method is used to get length of a string, in fact JavaScript returns number of code units occupied by the string. Therefore if we try to get length of Unicode character (which is 32-bits long), result will be as follow:
const emoji = "😎";
console.log(emoji.length); // Output will be 2
If you need to calculate length of Unicode or other multi-byte characters, you can use spread operator to splits the string into codepoints:
const emoji = "😎";
console.log([...emoji].length); // Output will be 1
or Array.from
method (we covered both of these situations when we tried to explain how to reverse a string in JavaScript):
const emoji = "😎";
console.log(Array.from(emoji).length); // Output also will be 1
Conclusion
In conclusion, getting the length of a string is a simple but important task when working with JavaScript strings. In this blog post, we covered different ways to get the length of a string in JavaScript, including the built-in length
and the use of the spread operator or Array.from()
method. We hope this guide has been helpful. Feel free to leave a comment if you have any questions or suggestions. Happy coding!
Leave a Reply