π 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 (12)
+1
Didn't thought about the
Object.assign
approach, nice! As mentioned in other comments, we need to consider that some characters such as emojis return their parts, for example:BTW, you can get syntax highlight in the code snippet on your post by adding the language after the triple back-tick.
Cheers!
it's not only emojis, but also many languages like chinese, japanese,... languages don't use alphabet, maybe cause errors.
Indeed. Mainly what I meant with "some characters like emojis" ... that's the easiest example, but there are lots of character sets that would produce errors -.-
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)here.
plus one useless trick:
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π .
What is object ? In the 4th type
Useful, Thank You β
string.split() and array.join() are easy to remember and usefull too