🐞 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
Woa ...
Object.assign([],str);... wouldn't ever have fathomed that something like that would work, in this way! (I wasn't even aware thatObject.assignto 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
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😅.
plus one useless trick:
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
string.split() and array.join() are easy to remember and usefull too
Useful, Thank You ✌