How to get character array from a string?
The spread
Syntax
You can use the spread syntax, an Array Initializer introduced in ECMAScript 2015 (ES6) standard:
var arr = [...str];
Examples
function a() {
return arguments;
}
var str = 'Hello World';
var arr1 = [...str],
arr2 = [...'Hello World'],
arr3 = new Array(...str),
arr4 = a(...str);
console.log(arr1, arr2, arr3, arr4);
The first three result in:
["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
The last one results in
{0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "W", 7: "o", 8: "r", 9: "l", 10: "d"}
Browser Support
Check the ECMAScript ES6 compatibility table.
Further reading
- MDN: Spread operator
- ECMAScript 2015 (ES6): 12.2.5 Array Initializer
spread
is also referenced as "splat
" (e.g. in PHP or Ruby or as "scatter
" (e.g. in Python).
Demo
Try before buy
You can also use Array.from
.
var m = "Hello world!";
console.log(Array.from(m))
This method has been introduced in ES6.
Reference
Array.from
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);
Array.from
const a = Array.from('ðððð');
console.log(a);
RegExp u
flag
const a = 'ðððð'.split(/(?=[\s\S])/u);
console.log(a);
Use /(?=[\s\S])/u
instead of /(?=.)/u
because .
does not match
newlines. If you are still in ES5.1 era (or if your browser doesn't
handle this regex correctly - like Edge), you can use the following alternative
(transpiled by Babel). Note, that Babel tries to also handle unmatched
surrogates correctly. However, this doesn't seem to work for unmatched low
surrogates.
const a = 'ðððð'.split(/(?=(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/);
console.log(a);
Reduce method (already answered by Mark Amery)
const s = 'ðððð';
const a = [];
for (const s2 of s) {
a.push(s2);
}
console.log(a);
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.