String To Array In Javascript

Converting a string to an array in Javascript.

Javascript is a widespread used technology for finding solutions to problems. At one point or the other in our problem solving process, we need to manipulate data to achieve a goal. Here we want to convert a string to an array.

What is a string?

A string is a series of characters like alphabets, number, special characters etc. A string is enclosed in a quote, either single quotes or double quotes.

What is an array?

An array is identified by the box-bracket [ ]. An array can enclose a set of strings or numbers as the case may be. It is used to store different elements.

How do we convert a string to an Array in Javascript?

There are four 'well-known' approach to achieve this. Which are;

  1. The javascript Array.from method
  2. Split method
  3. Object.assign method
  4. Spread operator

Let's declare a string as an example here;

const string = 'word';

  1. Array.from method: The Array from method is a javascript method used to convert a string to an array. It let's you shallow-copied Array instance from an array-like or iterable object.

    The syntax is Array.from(string);

    string: is the declared const string above.

  2. Split method: The Javascript split method divides a String into an ordered list of substrings and put's it in an array-like structure

    The syntax is string.split('');

    string: is the declared const string above.

  3. Object.assign method: This takes in two values which is the and empty array and the declared string.

    The syntax is Object.assign([], string);

  4. Spread operator: This is commonly used to make shallow copies of Javascript objects. It takes in an iterable object and expands it into individual elements.

    The syntax is [...string];

    string: is the declared const string above.

The above approaches results in :

// ['w', 'o', 'r', 'd']

Converting an empty string to an array results in an empty array.

PS: You can try it out in your browser console or any terminal that runs Javascript codes.

Benjamin Alamu's photo

Nice work boss

GriseldaKnight's photo

I was looking for exactly this, and it pops up on my feed. Thank you for this piece!🙌