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','!']
The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.
You need a return statement at the end of your method to return the char array. Also you can eliminate the endloop int variable and just declare your for loop like this.
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.
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.
const a = [...'ππππ']; console.log(a);
const a = Array.from('ππππ'); console.log(a);
u
flagconst 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);
const s = 'ππππ'; const a = []; for (const s2 of s) { a.push(s2); } console.log(a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With