How to get character array from a string?
Solution 1:
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.
Solution 2:
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);
Solution 3:
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
Solution 4:
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