How to Get Character Array from a String?

How to Get Character Array from a String?

How do you convert a string to a character array in JavaScript?

I'm thinking getting a string like "Hello world!" to the array
['H','e','l','l','o',' ','w','o','r','l','d','!']

14 Answers

Note: This is not unicode compliant. "I💖U".split('') results in the 4 character array ["I", "�", "�", "u"] which can lead to dangerous bugs. See answers below for safe alternatives.

Just split it by an empty string.

var output = "Hello world!".split('');
console.log(output);

See the String.prototype.split() MDN docs.

4

As hippietrail suggests, meder's answer can break surrogate pairs and misinterpret “characters.” For example:

// DO NOT USE THIS!
const a = '𝟘𝟙𝟚𝟛'.split('');
console.log(a);
// Output: ["�","�","�","�","�","�","�","�"]

I suggest using one of the following ES2015 features to correctly handle these character sequences.

Spread syntax (already answered by insertusernamehere)

const a = [...'𝟘𝟙𝟚𝟛'];
console.log(a);
Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.