6 Ways to Convert a String to an Array in JavaScript

sanchithasr

Sanchithasr

Posted on September 24, 2022

6 Ways to Convert a String to an Array in JavaScript

Arrays are the most powerful data structure in JavaScript. I found myself solving many algorithms by converting strings to arrays. So I thought of consolidating and comparing various ways to do the same.

Converting from string to array is always done using the split() method but after ES6, there are many tools we could do the same. Let’s go through each method one by one and discuss the pros and cons of each.

1. Using .split(β€˜β€™):

split() is a string method that splits a string into an array of the ordered list with a pattern. This is an ES6 method and is the cleanest way to get the job done.



////* Seperate string by space character(' ') *////

const myFavShow = 'The Office';
const myFavShowArray = myFavShow.split('');
console.log(myFavShowArray) 
//['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']


Enter fullscreen mode Exit fullscreen mode

Another advantage of this way is we can separate strings by characters or whitespace. Below is an example of how we can do it.



////* Seperate string by whitespace(' ') *////
const myFavShow = 'The Office';
const myFavShowArray = myFavShow.split(' ');
console.log(myFavShowArray) //['The', 'Office']

////* Seperate string by a character '-' *////
const favDialogue = 'Thats-what-she-said';
const favDialogueArr = favDialogue.split('-');
console.log(favDialogueArr) //['Thats', 'what', 'she', 'said']


Enter fullscreen mode Exit fullscreen mode

It also works well with Regex too. You can find the complete documentation of split() here.

This way flawlessly separates the string elements into an array but it has its limitations.

NOTE: This method does not work very well with uncommon Unicode characters. This method returns the Unicode of the characters instead of actual characters which might make our job a bit more complicated(refer here) but the MDN document has been updated so that we can make it work with Unicode if we just include u flag. See here for more information.



"πŸ˜„πŸ˜„".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"πŸ˜„πŸ˜„".split(/(?:)/u); // [ "πŸ˜„", "πŸ˜„" ]


Enter fullscreen mode Exit fullscreen mode

2. Using spread syntax ([…str])

This is the ES2015 feature that makes the transition very easy.



const myFavShow = 'The Office'

const myFavShowArray = [...myFavShow]

console.log(myFavShowArray) 
// ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']


Enter fullscreen mode Exit fullscreen mode

It also helps that the limitation we have in the split() has been eliminated here. Consider the below example. We can split any characters easily using this method.



const animal = '🦊🦊'
const animalArr = [...animal]
console.log(animalArr) // ['🦊', '🦊']


Enter fullscreen mode Exit fullscreen mode

3. Using Array.from(str):

The Array. from() method creates a new, shallow-copied Array instance from an iterable or array-like object.



const myFavShow = 'The Office'

const myFavShowArray = Array.from(myFavShow);

console.log(myFavShowArray) 
// ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']


Enter fullscreen mode Exit fullscreen mode

This method will not cause any issues when dealing with uncommon characters.



const str = '😎😎'
const arr = Array.from(str)
console.log(arr)


// ['😎', '😎']


Enter fullscreen mode Exit fullscreen mode

4. Using Object.assign([], str)

The Object. assign() method copies all the properties from one or more source objects to a target object. There are two things to keep in mind about this method though. One is that Object. assign() copies property values called deep copy (Refer here to know the difference between deep copy and shallow copy). One has to keep this in mind before using this method before using it.



const myFavShow = 'The Office'

const myFavShowArray = Object.assign([], myFavShow);

console.log(myFavShowArray) 
// ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']


Enter fullscreen mode Exit fullscreen mode

Another is that we have the same trouble as the split() method: it cannot separate uncommon characters (we see Unicode instead of actual characters).



const s = 'πŸ˜„πŸ˜„'
const a = Object.assign([], s);
console.log(a) // ['\uD83D', '\uDE04', '\uD83D', '\uDE04']


Enter fullscreen mode Exit fullscreen mode

5. Using old school method (for loop and array.push())

Although we have a lot of options to play around with, I had to mention this old-school method where we push the elements of the string using the for loopand array method push().

This is not the cleanest way of doing it but it is most definitely worth mentioning who want to stay away from the changing complexities of JavaScript (Although I would prefer other ways).



const s = 'the office';
const a = [];
for (const s2 of s) {
   a.push(s2);
}
console.log(a); 
// ['t', 'h', 'e', ' ', 'o', 'f', 'f', 'i', 'c', 'e']


Enter fullscreen mode Exit fullscreen mode

Also, it works very well with uncommon (Unicode) characters. Look at the below example.



const s = 'πŸ˜πŸ™πŸšπŸ›πŸ˜„πŸ˜„';
const a = [];
for (const s2 of s) {
   a.push(s2);
}
console.log(a); //['𝟘', 'πŸ™', '𝟚', 'πŸ›', 'πŸ˜„', 'πŸ˜„']


Enter fullscreen mode Exit fullscreen mode

6. Using Array.prototype.slice.call(β€˜string’)

Refer to this blog to understand more about .slice.call()method.



const favShow = Array.prototype.slice.call("The Office!");
console.log(favShow); //['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e', '!']


Enter fullscreen mode Exit fullscreen mode

This method also has the same problem as the split() method so be aware while using it.



const favShow = Array.prototype.slice.call("πŸ˜„πŸ˜„");
console.log(favShow); //['\uD83D', '\uDE04', '\uD83D', '\uDE04']

Enter fullscreen mode Exit fullscreen mode




References:

Conclusion:

To sum it all up, below are the ways we can do the job.

Consolidated ways

That’s 6 ways to convert string to array in JavaScript. Comment below if you used any other methods to get the job done.

Thank you for reading!

πŸ’– πŸ’ͺ πŸ™… 🚩
sanchithasr
Sanchithasr

Posted on September 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related