Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JavaScript字符串拆分为代码点数组?(考虑到“代理项对”,但不考虑“字素簇”)_Javascript_String_Unicode_Codepoint_Surrogate Pairs - Fatal编程技术网

将JavaScript字符串拆分为代码点数组?(考虑到“代理项对”,但不考虑“字素簇”)

将JavaScript字符串拆分为代码点数组?(考虑到“代理项对”,但不考虑“字素簇”),javascript,string,unicode,codepoint,surrogate-pairs,Javascript,String,Unicode,Codepoint,Surrogate Pairs,将JavaScript字符串拆分为“字符”可以很容易地完成,但如果您关心Unicode(并且您应该关心Unicode),则会出现问题 JavaScript本机将字符视为16位实体(),但这不允许在外部使用Unicode字符 要处理BMP之外的Unicode字符,JavaScript必须考虑“”,而它本机不考虑“” 我正在寻找如何按代码点拆分js字符串,无论代码点需要一个或两个JavaScript“字符”(代码单元)。 根据您的需要,按拆分可能不够,您可能希望按“”拆分,其中群集是一个基本代码点,

将JavaScript字符串拆分为“字符”可以很容易地完成,但如果您关心Unicode(并且您应该关心Unicode),则会出现问题

JavaScript本机将字符视为16位实体(),但这不允许在外部使用Unicode字符

要处理BMP之外的Unicode字符,JavaScript必须考虑“”,而它本机不考虑“”

我正在寻找如何按代码点拆分js字符串,无论代码点需要一个或两个JavaScript“字符”(代码单元)。

根据您的需要,按拆分可能不够,您可能希望按“”拆分,其中群集是一个基本代码点,后跟其所有非间距修改器代码点,例如


出于这个问题的目的,我不需要按grapheme cluster进行拆分。

在ECMAScript 6中,您可以使用字符串作为迭代器来获取代码点,或者您可以搜索字符串以查找
//ug
,或者您可以反复调用
getCodePointAt(I)

不幸的是,的
语法和regexp标志的
不能进行多填充,调用多填充的
getCodePoint()
会非常慢(O(n²)),因此我们暂时还不能实际使用这种方法

因此,采用手动方式:

String.prototype.toCodePoints= function() {
    chars = [];
    for (var i= 0; i<this.length; i++) {
        var c1= this.charCodeAt(i);
        if (c1>=0xD800 && c1<0xDC00 && i+1<this.length) {
            var c2= this.charCodeAt(i+1);
            if (c2>=0xDC00 && c2<0xE000) {
                chars.push(0x10000 + ((c1-0xD800)<<10) + (c2-0xDC00));
                i++;
                continue;
            }
        }
        chars.push(c1);
    }
    return chars;
}
String.prototype.toCodePoints=function(){
字符=[];
对于(var i=0;i=0xD800&&c1@bobince的答案(幸运的)有点过时了;您现在只需使用

var chars = Array.from( text )

要获得一个单码点字符串列表,该列表不考虑astral/32位/代理Unicode字符。

按照@John Frazer的回答,可以使用这种甚至简洁的字符串迭代形式:

const chars = [...text]
e、 例如:

const text = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A'
const chars = [...text] // ["A", "Another method using codePointAt:

String.prototype.toCodePoints = function () {
  var arCP = [];
  for (var i = 0; i < this.length; i += 1) {
    var cP = this.codePointAt(i);
    arCP.push(cP);
    if (cP >= 0x10000) {
      i += 1;
    }
  }
  return arCP;
}
const text='A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A'

const chars=[…text]/[“A”,“另一个使用codePointAt的方法:

String.prototype.toCodePoints=函数(){
var-arCP=[];
对于(变量i=0;i=0x10000){
i+=1;
}
}
返回弧电位;
}

getCodePointAt
O(n)
。它接受的参数不是代码点索引,而是代码单位索引(常规字符串索引)。@glebm您的意思是
getCodePointAt
O(1)
?是的,
O(1)
,我不能再编辑注释了。如果您喜欢简洁的话,最好的答案。这也适用于将实际图形符号粘贴到字符串中的情况(如果您的IDE支持)