DEV Community

Cover image for 4 ways to convert a string to an array in Javascript
Maria Antonella 🦋
Maria Antonella 🦋

Posted on

4 ways to convert a string to an array in Javascript

🐞 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 '] 

Enter fullscreen mode Exit fullscreen mode

👾 So simple! But they are those things that I google every day because I never remember.😅

Top comments (10)

Collapse
 
felipperegazio profile image
Felippe Regazio

+1

Object.values(str);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lionelrowe profile image
lionel-rowe

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! 🙃

Collapse
 
leob profile image
leob • Edited

Woa ... Object.assign([],str); ... wouldn't ever have fathomed that something like that would work, in this way! (I wasn't even aware that Object.assign to an array would do anything that makes sense)

Collapse
 
incrementis profile image
Akin C.

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😅.

Collapse
 
danibarria profile image
Jose Daniel Barria Reyes

here.

const range = '[2,3]';

const [min, max] = JSON.parse(range);

// prints 2 3
console.log(min,max);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mixrich profile image
Mikhail Rychagov

plus one useless trick:

[].map.call("foo", c => c); // ["f", "o", "o"]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tanth1993 profile image
tanth1993

it's not only emojis, but also many languages like chinese, japanese,... languages don't use alphabet, maybe cause errors.

Collapse
 
madhutammisetti profile image
madhutammisetti

What is object ? In the 4th type

Collapse
 
zaselalk profile image
Asela

Useful, Thank You ✌

Collapse
 
mohdahmad1 profile image
Mohd Ahmad

string.split() and array.join() are easy to remember and usefull too