String.length
- Published
- Reading time
- 2 min read
- Length
- 320 words
On this page
What is String.length in JavaScript?#
String.length is a property in JavaScript that returns the length of a string. The length of a string is the number of characters in it.
For example, if the string is "Hello", then the length of the string is 5.
Using String.length in JavaScript#
To use String.length in JavaScript, you simply need to call it on a string:
let myString = "Hello";
console.log(myString.length); // Output: 5In the above example, we first define a variable named 'myString' and assign it a value of "Hello". We then call 'myString.length' and log the result to the console, which is 5.
Other ways to get the length of a string#
Aside from using String.length, there are other ways to get the length of a string in JavaScript. One way is to convert the string to an array and then use the array's length property:
let myString = "Hello";
let myArray = Array.from(myString); // Convert string to array
console.log(myArray.length); // Output: 5In the above example, we first define a variable named 'myString' and assign it a value of "Hello". We then convert the string to an array using the Array.from() method and assign it to a new variable named 'myArray'. We then log 'myArray.length' to the console, which is 5.
Another way to get the length of a string is to split the string into an array using a separator and then use the resulting array's length property:
let myString = "Hello";
let myArray = myString.split(""); // Split string into array
console.log(myArray.length); // Output: 5In the above example, we first define a variable named 'myString' and assign it a value of "Hello". We then split the string into an array using an empty string as the separator and assign it to a new variable named 'myArray'. We then log 'myArray.length' to the console, which is 5.