π 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.π
Latest comments (12)
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.
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
+1
plus one useless trick:
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)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
Useful, Thank You β
string.split() and array.join() are easy to remember and usefull too