一个字符可能由多个码元组成,js 真实的字符=计算长度、获取第几个字符、截取字符

//计算真正字符长度
String.prototype.pointLength = function () {
    let len = 0;
    for (let i = 0; i < this.length;) {
        len++;
        const point = this.codePointAt(i);
        i += point > 0xffff ? 2 : 1;
    }
    return len;
}
//获取第几个字符
String.prototype.pointAt = function (index) {
    let curIndex = 0;
    for (let i = 0; i < this.length;) {
        if(curIndex === index) {
            const point = this.codePointAt(i);
            return String.fromCodePoint(point);
        }
        curIndex++;
        const point = this.codePointAt(i);
        i += point > 0xffff ? 2 : 1;
    }
}
//截取字符
String.prototype.pointSlice = function (start,end=this.pointLength()) {
    let result = '';
    const len = this.pointLength();
    for (let i = start; i < len && i < end; i++) {
        result += this.pointAt(i);
    }
    return result;
}

你可能感兴趣的:(js,javascript,前端,开发语言)