How do you get a string to a character array in JavaScript?
-
13-10-2019 - |
Question
How do you get 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','!']
Solution
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.
OTHER TIPS
Since this question is originally asked more than five years ago, people are still misopetating this type of task. As hippietrail suggests, meder's answer can break surrogate pairs and misinterpret “characters.” For example:
// DO NOT USE THIS!
> '𝟘𝟙𝟚𝟛'.split('')
[ '�', '�', '�', '�', '�', '�', '�', '�' ]
I suggest using one of the following ES2015 features to correctly handle these character sequences.
Spread-operator (already answered by insertusernamehere)
> [...'𝟘𝟙𝟚𝟛']
[ '𝟘', '𝟙', '𝟚', '𝟛' ]
Array.from
> Array.from('𝟘𝟙𝟚𝟛')
[ '𝟘', '𝟙', '𝟚', '𝟛' ]
RegExp u
flag
> '𝟘𝟙𝟚𝟛'.split(/(?=[\s\S])/u)
[ '𝟘', '𝟙', '𝟚', '𝟛' ]
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 this alternative (transpiled by Babel):
> '𝟘𝟙𝟚𝟛'.split(/(?=(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/);
[ '𝟘', '𝟙', '𝟚', '𝟛' ]
Note, that Babel tries to also handle unmatched surrogates correctly. However, this doesn't seem to work for unmatched low surrogates.
Test all in your browser:
function run_test(){
str=document.getElementById('nonBMP').checked ? '𝟘_NL_𝟙_HIGH_𝟚_LOW_𝟛' : '0_NL_1_HIGH_2_LOW_3';
str=str.replace('_NL_' ,document.getElementById('nl' ).checked ? '\n' : '');
str=str.replace('_HIGH_',document.getElementById('high').checked ? '𝟘'.charAt(0) : '');
str=str.replace('_LOW_' ,document.getElementById('low' ).checked ? '𝟘'.charAt(1) : '');
//wrap all examples into try{ eval(...) } catch {} to aloow script execution if some syntax not supported (for example in Internet Explorer)
document.getElementById("testString" ).innerText=JSON.stringify(str);
try { document.getElementById("splitEmpty" ).innerText=JSON.stringify(eval('str.split("")')); } catch(err) { }
try { document.getElementById("splitRegexDot").innerText=JSON.stringify(eval('str.split(/(?=.)/u)')); } catch(err) { }
try { document.getElementById("spread" ).innerText=JSON.stringify(eval('[...str]')); } catch(err) { }
try { document.getElementById("arrayFrom" ).innerText=JSON.stringify(eval('Array.from(str)')); } catch(err) { }
try { document.getElementById("splitRegex" ).innerText=JSON.stringify(eval('str.split(/(?=[\\s\\S])/u)')); } catch(err) { }
try { document.getElementById("splitBabel" ).innerText=JSON.stringify(eval('str.split(/(?=(?:[\\0-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]))/)')); } catch(err) { }
}
document.getElementById('runTest').onclick=run_test;
th, td {
border: 1px solid black;
padding: 4px;
}
<div><input type="checkbox" id="nonBMP" checked /><label for="nonBMP">Codepoints above U+FFFF</label></div>
<div><input type="checkbox" id="nl" checked /><label for="nl" >Newline</label></div>
<div><input type="checkbox" id="high" /><label for="high" >Unmached high surrogate</label></div>
<div><input type="checkbox" id="low" /><label for="low" >Unmached low surrogate</label></div>
<button type="button" id="runTest">Run Test!</button>
<table>
<tr><td>str=</td> <td><div id="testString"></div></td></tr>
<tr><th colspan="2">Wrong:</th></tr>
<tr><td>str.split("")</td> <td><div id="splitEmpty"></div></td></tr>
<tr><td>str.split(/(?=.)/u)</td> <td><div id="splitRegexDot"></div></td></tr>
<tr><th colspan="2">Better:</th></tr>
<tr><td>[...str]</td> <td><div id="spread"></div></td></tr>
<tr><td>Array.from(str)</td> <td><div id="arrayFrom"></div></td></tr>
<tr><td>str.split(/(?=[\s\S])/u)</td> <td><div id="splitRegex"></div></td></tr>
<tr><td>str.split(/(?=(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/)</td><td><div id="splitBabel"></div></td></tr>
</table>
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
spread
is also referenced as "splat
" (e.g. in PHP or Ruby or as "scatter
" (e.g. in Python).
Demo
It already is:
var mystring = 'foobar';
console.log(mystring[0]); // Outputs 'f'
console.log(mystring[3]); // Outputs 'b'
Or for a more older browser friendly version, use:
var mystring = 'foobar';
console.log(mystring.charAt(3)); // Outputs 'b'
You can also use Array.from
.
var m = "Hello world!";
console.log(Array.from(m))
This method has been introduced in ES6.
Reference
This is an old question but I came across another solution not yet listed.
You can use the Object.assign function to get the desired output:
var output = Object.assign([], "Hello, world!");
console.log(output);
// [ 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!' ]
Not necessarily right or wrong, just another option.
You can iterate over the length of the string and push the character at each position:
const str = 'Hello World';
const stringToArray = (text) => {
var chars = [];
for (var i = 0; i < text.length; i++) {
chars.push(text[i]);
}
return chars
}
console.log(stringToArray(str))
simple answer:
let str = 'this is string, length is >26';
console.log([...str]);
Array Map is also a good option
const name = "Hello World !"
const map = Array.prototype.map
const arr = map.call(name, single => {
return `${single}`
})
console.log(arr)
How about this?
function stringToArray(string) {
let length = string.length;
let array = new Array(length);
while (length--) {
array[length] = string[length];
}
return array;
}