如果slice对于正常的字符串的使用是没有问题里,例如:
const str = '这里是荷逸啊';
console.log(str.slice(3,5));//荷逸
但是如果是特殊字符串就不可以了
const str = '阿是𠮷娃娃🐱他说的纷';
console.log(str.slice(3, 6));//�娃娃
需要在进行封装一下
创建js文件 sliceByPoint.js
String.prototype.sliceByPoint = function (pStart, pEnd) {
let result = ''; // 截取的结果
let pIndex = 0; // 码点的指针
let cIndex = 0; // 码元的指针
while (true) {
if (pIndex >= pEnd || cIndex >= this.length) {
break;
}
const point = this.codePointAt(cIndex);
if (pIndex >= pStart) {
result += String.fromCodePoint(point);
}
pIndex++;
cIndex += point > 0xffff ? 2 : 1;
}
return result;
};
使用方式
import 'sliceByPoint'
const str = '阿是𠮷娃娃🐱他说的纷';
console.log(str.sliceByPoint(3, 6));//娃娃🐱