Skip to content
the poor coder

String.length

Poor Man
Published
Reading time
2 min read
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:

Text

let myString = "Hello";
console.log(myString.length); // Output: 5

In 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:

Text

let myString = "Hello";
let myArray = Array.from(myString); // Convert string to array
console.log(myArray.length); // Output: 5

In 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:

Text

let myString = "Hello";
let myArray = myString.split(""); // Split string into array
console.log(myArray.length); // Output: 5

In 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC