问题
For long time we used naive approach to split strings in JS:
someString.split('');
But popularity of emoji forced us to change this approach - emoji characters (and other non-BMP characters) like 😂 are made of two "characters'.
String.fromCodePoint(128514).split(''); // array of 2 characters; can't embed due to StackOverflow limitations
So what is modern, correct and performant approach to this task?
回答1:
The best approach to this task is to use native String.prototype[Symbol.iterator]
that's aware of Unicode characters. Consequently clean and easy approach to split Unicode character is Array.from
used on string, e.g.:
const string = String.fromCodePoint(128514, 32, 105, 32, 102, 101, 101, 108, 32, 128514, 32, 97, 109, 97, 122, 105, 110, 128514);
Array.from(string);
回答2:
This question has already been answered but I think it's worth mentioning spread operator way.
let str="I can split unicode also ☺🤖😸 ";
console.log([...str]);
来源:https://stackoverflow.com/questions/35223206/how-to-split-unicode-string-to-characters-in-javascript