Contents

About converting strings to arrays

   Jan 12, 2024     1 min read

About “How to convert a string to an array”

While testing our code, we realized that there are many ways to convert strings to arrays.

We’d like to share them with you.

How to make an array using a for statement

const str = "Hello";
const arr = [];

for (let i = 0; i < str.length; i++) {
  arr.push(str[i]);
}

console.log(arr); // ["H", "e", "l", "l", "o"]

In the above code, the for loop is used to increment the i variable by 1, starting at 0, up to str.length, while adding each character of str to the array arr using the push method.

This ensures that each character of the string is pushed into each element of the array.

When you run the above example, the string “Hello” is converted to an array, stored in the arr variable, and the array is output via console.log(arr).

The output will be [“H”, “e”, “l”, “l”, “o”].

How to create an array using the split statement

const str = "Hello";
const arr = str.split(""); // Convert a string to an array using an empty string as a separator
console.log(arr); // ["H", "e", "l", "l", "o"]

This is similar to the for statement, so I’ll skip explaining it.

How to take an array literal and make it an array

const str = "Hello";
const arr = [...str]; // Convert a string to an array using array literals
console.log(arr); // ["H", "e", "l", "l", "o"]