//计算真正字符长度
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 真实的字符=计算长度、获取第几个字符、截取字符
最新推荐文章于 2025-03-17 15:31:33 发布
本文介绍了如何在JavaScript中扩展String对象的方法,包括计算字符串的实际字符长度(考虑多字节字符),获取指定编码点的字符,以及截取特定范围的字符。
405

被折叠的 条评论
为什么被折叠?



