DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 (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
Luke Shiru

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.

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!