Syntax of “length” property
It’s a built-in property and it returns the length a given string. It counts number of characters, including spaces, and returns a number.
It also counts the spaces (blank spaces) in between the string or anything inside the opening and closing quotes (Note: You can use single or double quotes).
Let's find the Length of a String
<body> <p id='p1'></p> </body> <script> let my_intro = new String('Hi, my name is Arun Banik and welcome to my blog.'); document.getElementById('p1').innerHTML = 'The string: ' + my_intro; document.getElementById('p1').innerHTML = document.getElementById('p1').innerHTML + '<br /> The length of the string: <b>' + my_intro.length + '</b>'; </script>
If the string has more spaces, it will count it too. For example,
let my_intro = new String('Hi, my name is Arun Banik and welcome to my blog.');
The length of the above string is now 52. Since, I have added two spaces after the word is.
Now let’s try with special characters. A string can be anything.
<script> let str = new String('1 % 5 ='); document.write (str.length); </script>
The output would be 7.
Length of Empty string
If a string is empty, the length property would return a zero. For example,
let str = new String('');
Get the length of a String in a Variable
In the above examples, I have used the String() function to define a string value and then get the length. However, if you are storing data in a variable, you can still use the length property with a variable to get the length of the string. For example,
<script> let str; str = 'Hello, Welcome to my blog :-)'; document.write (str.length); </script>
Or, using a const …
const str = 'Hello, Welcome to my blog :-)';
Remember, a string is any text or data that is stored within a single quote or a double quote. The length property works with a string and the string can be used with a String() method or a variable.
Thanks for reading ☺.