Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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','!']

like image 811
DarkLightA Avatar asked Dec 28 '10 16:12

DarkLightA


People also ask

Can we convert a string to character array in Java?

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.

How can one create an array of characters from a string in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

How do you return a character array in Java?

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.


2 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.

like image 157
meder omuraliev Avatar answered Sep 17 '22 09:09

meder omuraliev


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);
like image 23
hakatashi Avatar answered Sep 18 '22 09:09

hakatashi