DEV Community

Cover image for String To Array In One Line : JavaScript
shivamkapasia0
shivamkapasia0

Posted on

String To Array In One Line : JavaScript

Hey folks!
we can easily convert String into an array by using spread operator (...) :

const string = 'Shivam Kapasia';
const array = [...string];
console.log(`${array}`); // S,h,i,v,a,m, ,K,a,p,a,s,i,a
Enter fullscreen mode Exit fullscreen mode

Note : The array will also include space, but if you don't want to store space in array first remove space from string then use spread operator.

What’s your preferred way to convert string into an array ?

Top comments (5)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Depends really why you want to convert it? Since a string is already iterable, for a lot of use cases the conversion is not necessary

Collapse
 
shivamkapasia0 profile image
shivamkapasia0

Agreed!

Collapse
 
akashkava profile image
Akash Kava

And all of array methods are generic and can be called on string with call or apply.

Collapse
 
lgrammel profile image
Lars Grammel

You could also use str.split('')

Collapse
 
shivamkapasia0 profile image
shivamkapasia0

Thanks for highlighting this, will definitely try with Intl.Segmenter.