码元和码点(字符串截取截取得是码元,汉字有一些偏僻字占据两个码元,字符的函数往往不是我们期待)

const str = '你是一个𠮷娃娃😻的小可爱'

console.log(str.slice(5,9)) //�娃娃�

console.log('😻'.length) //2

String.prototype.sliceByPoint = function(pStart,pEnd){

    let result = '' //截取的结果

    let pIndex = 0 //码点的指针

    let cIndex = 0 //码元的指针

    while(1){

        if (pIndex >= pEnd || cIndex >= this.length) {

            break

        }

       

        const point = this.codePointAt(cIndex) //point > 0xffff 大小决定是否占两个码元,codePointAt函数用于检索字符串中特定位置的字符的Unicode代码点

        if(pIndex>=pStart){

            result+=String.fromCodePoint(point)

        }

        pIndex++

        cIndex += point > 0xffff ? 2:1

    }

    return result

}

console.log('111',str.sliceByPoint(5,8)) //娃娃😻

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值