DEV Community

Cover image for 4 Ways to Convert String to Character Array in JavaScript
Samantha Ming
Samantha Ming

Posted on • Originally published at samanthaming.com

4 Ways to Convert String to Character Array in JavaScript

Alt Text

Here are 4 ways to split a word into an array of characters. "Split" is the most common and more robust way. But with the addition of ES6, there are more tools in the JS arsenal to play with 🧰

I always like to see all the possible ways to solve something because then you can choose the best way for your use case. Also, when you see it pop up in someone's code base, you will understand it with ease πŸ‘β€¬

const string = 'word';

// Option 1
string.split('');

// Option 2
[...string];

// Option 3
Array.from(string);

// Option 4
Object.assign([], string);

// Result:
// ['w', 'o', 'r', 'd']

Scenarios

Instead of going through the pros and cons of each different way. Let me show you the different scenarios where one is preferred over the other.

Array of Characters

If all you're doing is wanting separate the string by each string character, all of the ways are good and will give you the same result

const string = 'hi there';

const usingSplit = string.split('');
const usingSpread = [...string];
const usingArrayFrom = Array.from(string);
const usingObjectAssign = Object.assign([], string);

// Result
// [ 'h', 'i', ' ', 't', 'h', 'e', 'r', 'e' ]

Specific Separators

If you want to split your string by a specific character, then split is the way to go.

const string = 'split-by-dash';

const usingSplit = string.split('-');
// [ 'split', 'by', 'dash' ]

The other ways are limited by each string character only

const string = 'split-by-dash';

const usingSpread = [...string];
const usingArrayFrom = Array.from(string);
const usingObjectAssign = Object.assign([], string);

// Result:
// [ 's', 'p', 'l', 'i', 't', '-', 'b', 'y', '-', 'd', 'a', 's', 'h' ]

Strings containing Emojis

If your strings contain emojis, then split or Object.assign might not be the best choice. Let's see what happens:

const string = 'cakeπŸ˜‹';

const usingSplit = string.split('');
const usingObjectAssign = Object.assign([], string);

// Result
// [ 'c', 'a', 'k', 'e', 'οΏ½', 'οΏ½' ]

However, if we use the other ways, it works :

const usingSpread = [...string];
const usingArrayFrom = Array.from(string);

// Result
// [ 'c', 'a', 'k', 'e', 'πŸ˜‹' ]

This is because split separates characters by UTF-16 code units which are problematic because emoji characters are UTF-8. If we look at our yum emoji 'πŸ˜‹' it's actually made up of 2 characters NOT 1 as we perceive.

'πŸ˜‹'.length; // 2

This is what's called grapheme clusters - where user perceives it as 1 single unit, but under the hood it's in fact made up of multiple units. The newer methods spread and Array.from are better equipped to handle these and will split your string by grapheme clusters πŸ‘

A caveat about Object.assign ⚠️

One thing to note Object.assign is that it doesn't actually produce a pure array. Let's start with its definition

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object

The key there is "copies all enumerable own properties". So what we're doing here Object.assign([], string) it copying ALL of our string properties over to our new array. Which means we have an Array PLUS some string methods.

TypeScript Test: Result array is not a string[] type 😱

This is more evident if we use the TypeScript Playgound. Feel free to copy the code and paste in the playground, where you can hover on the variable to view the types. Since this is just an article, I'll paste the result here so you can follow along.

const word = 'word';

const usingSplit = string.split('');
const usingSpread = [...string];
const usingArrayFrom = Array.from(string);

// Result:
// string[] πŸ‘ˆ Which means it's an Array of strings

However, if we look at the result type of Object.assign. It doesn't give us an Array of strings.

const usingObjectAssign = Object.assign([], string);

// Result:
// never[] & "string" πŸ‘ˆ which means NOT Array of strings 😱

TypeScript Test: Result array can access string properties 😱

We can do further check this by accessing a property that should only be available to a String.

const string = 'string';
const array = [];

string.bold; // βœ…(method) String.bold(): string
array.bold; //  ❌Property 'bold' does not exist on type

So that means if I call bold on our Array, it should tell us this property doesn't exist. This is what we expect to see:

Array.from('string').bold;
// Property 'bold' does not exist on type

BUT, if we call bold on our supposedly Array created by Object.assign, it works 😱

Object.assign([], 'string').bold;
// (method) String.bold(): string

☝️ And this is because Object.assign copies over ALL the properties over from the original String. Here's how I'd explain it in non-dev terms. You go to a store to buy a dog. But then store Object.assign sells you a dog that has dragon wings. Which sounds super cool, but this isn't really a rental friendly pet. Hmm...I don't think this is my best example. But I think you get my point πŸ˜‚

Conversion seems okay in browser πŸ™‚

Now I don't think this is a major deal breaker, cause:

It seems that browsers have some kind of mechanism in place to "safely" do Object.assign([], "string") and avoid adding the methods of that string to the array.

Thank you @lukeshiru: for sharing this knowledge for me πŸ‘ He also created a TypeScript playground code so you can see > link

Community Input

[@CaptainOrion](https://twitter.com/captainorion_/status/1238979904567271425?s=21):_ Turn string into char Array but using map function 🀣

Array.prototype.map.call('word', eachLetter => eachLetter);

// ['w', 'o', 'r', 'd']

@HiUmesh2: Array.prototype.slice.call('string') wil do the trick too

@inside.code: Extra info: it's safer to use the spread operator (second method) rather than String.prototype.split('') (first method), because split() doesn't work with some uncommon characters.

@faerberrr: I had a string that contained special characters like Γ₯æāă etc. When I split them using the .split('') method and ran .length, it returned twice the expected value! Switching to the spread operator fixed the problem.

Resources


Thanks for reading ❀
Say Hello! Instagram | Twitter | SamanthaMing.com

Top comments (12)

Collapse
 
karataev profile image
Eugene Karataev

Thanks for the post! I didn't know that split method and spread operator have different behavior.
I looked at grapheme clusters one step deeper and learned that even ... may give wrong results for complex emojis.

console.log([...'πŸ³οΈβ€πŸŒˆ'].length) // 6 πŸ€”

There is even grapheme splitter library to break strings in characters as expected.

Collapse
 
aralroca profile image
Aral Roca

I didn't know that .bold exist! Heh

Collapse
 
samanthaming profile image
Samantha Ming

Ya, it does! But don't use it lol because it's deprecated. I just wanted to find a method that was only part of String and not an Array and that's the one I found. Which made me realize these two objects have similar methods πŸ˜‚

Collapse
 
martinadamsdev profile image
Martin Adams

Intersting and inspiring article!

Can I translate it into Chinese to help more developers?

I will give credit at the top of the article.

Collapse
 
samanthaming profile image
Samantha Ming

You bet Jack! My code notes aren't mean to be shared! Thank you so much for wanting to translate it πŸ‘

You can find the markdown and original image in my repo:
github.com/samanthaming/samanthami...

(I'd recommend checking the markdown in my repo because I keep that up to date, and sometimes I might forget to edit the article on dev πŸ˜…)

Let me know if you need anything that can help with your translation 😊

Collapse
 
martinadamsdev profile image
Martin Adams

ok. star and watch.

Collapse
 
thehanna profile image
Brian Hanna

This is so incredibly in depth! I always learn something new from your posts, and I've been using JS for more than 20 years! Thank you!

Collapse
 
samanthaming profile image
Samantha Ming

Thanks Brian! That makes me so happy to hear that you still learned something even with your extensive background. I want to follow your attitude, have that StudentMindset even after 20 years. I think it’s one of the thing I love about tech, it’s always evolving, so you never stop learning πŸ˜„πŸ‘

Collapse
 
raquelsartwork profile image
Raquel Santos | RS-coding

Thank you so much for your posts. really easy to understand . I am more visual person and your posts are amazing throw that. thank you !

Collapse
 
samanthaming profile image
Samantha Ming

Same! I just need to learn video editing and hopefully one day I can make video tutorials of these πŸ˜†

Thank you for your kind words, so glad you found my code notes helpful 😊 Btw, I also have a series where I try to explain common code interview questions using pictures that you might also like πŸ‘‰ samanthaming.com/pictorials/

Collapse
 
isajal07 profile image
Sajal Shrestha

I always loved your blogs. Keep it coming, Samantha. πŸ˜„

Collapse
 
samanthaming profile image
Samantha Ming

You bet! Thanks for the encouragement! So happy you found them helpful πŸ˜ŠπŸ‘