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 ?

Discussion (6)

Collapse
jonrandy profile image
Jon Randy • Edited on

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 Author

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
lukeshiru profile image
LUKESHIRU

Consider that this might have unexpected results with some emojis for example. Try using your function with this emoji: πŸ‘¨πŸΌβ€πŸ’» ... One good way of dealing with that is with Intl.Segmenter.

Cheers!

Collapse
shivamkapasia0 profile image
shivamkapasia0 Author

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