如何将Unicode字符串拆分为JavaScript

时间:2016-02-05 11:35:38

标签: javascript unicode

很长一段时间我们使用天真的方法在JS中分割字符串:

someString.split('');

但表情符号的普及迫使我们改变这种方法 - 表情符号(和其他非BMP字符)就像是由两个"字符组成的。

String.fromCodePoint(128514).split(''); // array of 2 characters; can't embed due to StackOverflow limitations

那么这项任务的现代,正确和高效的方法是什么?

3 个答案:

答案 0 :(得分:5)

使用spread in array literal

const str = "????";
console.log([...str]);

使用for...of

function split(str){
  const arr = [];
  for(const char of str)
    arr.push(char)
   
  return arr;
}

const str = "????";
console.log(split(str));

答案 1 :(得分:2)

此任务的最佳方法是使用了解Unicode字符的原生String.prototype[Symbol.iterator]。因此,在字符串上使用了Array.from的简洁方法来分割Unicode字符,例如:

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 :(得分:2)

ECMA 2015中引入了一个标志,以支持正则表达式中的unicode意识。

在正则表达式中添加u会返回结果中的完整字符。

const withFlag = `AB?DE`.match(/./ug);
const withoutFlag = `AB?DE`.match(/./g);

console.log(withFlag, withoutFlag);

还有更多here

相关问题