const str = 'Hello, my name is Tim'; // Outputs: 21 console.log(str.length);
In this article, I will explain, in detail, the String built-in length property, as well as show real-life examples.
Let’s get to it 😎.
The length property returns the number of characters in a string (in UTF-16 code units).
If the string is empty, this property will return 0.
This is a read-only property.
All major browsers support the length property 🥳. It is an ECMAScript1 feature (1997).
Here is a small example of the length property in action:
const str = 'Tim Mousk'; // Outputs: 9 console.log(str.length);
As you can see, the length property returns the number of characters in the str constant.
How to find the length without spaces?
To find the length of a string without spaces you can use a combination of the replace function with the length property.
const str = 'This is a long statement'; // First, we remove all the spaces from the string. const strWithoutSpaces = str.replace(/\s/g, ''); // Then, we use the length property. // Outputs: 20 console.log(strWithoutSpaces.length);
Why does string length return undefined?
The only reason why the length property might return undefined is that the object on which you are calling this property IS NOT a string.
Make sure, that the object's type is a string by using the typeof operator.
If you have any questions please ask them in the comments section.
I always check for new comments and answer them.
Thank you very much for reading this article.
Please share it with your fellow coders and colleagues.