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.πŸ˜…

Latest comments (12)

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
 
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
 
felipperegazio profile image
Felippe Regazio

+1

Object.values(str);
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
 
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
 
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
 
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