How to split Unicode string to characters in JavaScript

偶尔善良 提交于 2020-06-12 07:25:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!