DEV Community

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

Posted on

9 1

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay