6 Ways to Convert a String to an Array in JavaScript
Sanchithasr
Posted on September 24, 2022
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']
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']
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); // [ "π", "π" ]
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']
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) // ['π¦', 'π¦']
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']
This method will not cause any issues when dealing with uncommon characters.
const str = 'ππ'
const arr = Array.from(str)
console.log(arr)
// ['π', 'π']
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']
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']
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']
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); //['π', 'π', 'π', 'π', 'π', 'π']
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', '!']
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']
References:
- https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character
- https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402
- https://www.stevenchang.tw/blog/2020/05/23/JavaScript-slice-call-function
- MDN Web Docs: split
- MDN Web Docs: spread
- MDN Web Docs: Array.from
- MDN Web Docs: Object.assign
- https://www.samanthaming.com/tidbits/83-4-ways-to-convert-string-to-character-array
Conclusion:
To sum it all up, below are the ways we can do the job.
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!
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
November 28, 2024