🐞 Today I share with you four ways to convert a string to an array in JavaScript.
const str = 'antonella';
str.split('');
let newStr = [...str];
Array.from(str);
Object.assign([],str);
// ['a ', 'n ', ' t ', 'o ', ' n ', ' e ', ' l', ' l ', ' a ']
👾 So simple! But they are those things that I google every day because I never remember.😅
Top comments (10)
+1
Not all of the ways give the same results, depending on the input string.
I started writing this as a comment, but it turned into an article instead. Enjoy! 🙃
Gotchas when converting strings to arrays in JS
lionel-rowe ・ Aug 18 ・ 3 min read
Woa ...
Object.assign([],str);
... wouldn't ever have fathomed that something like that would work, in this way! (I wasn't even aware thatObject.assign
to an array would do anything that makes sense)Hello Maria Antonella 🦋,
thanks for your article.
It's very brief but very revealing :D.
"So simple! But they are those things that I google every day because I never remember." I can empathize with that too😅.
here.
plus one useless trick:
it's not only emojis, but also many languages like chinese, japanese,... languages don't use alphabet, maybe cause errors.
What is object ? In the 4th type
Useful, Thank You ✌
string.split() and array.join() are easy to remember and usefull too