字符串长度返回:1中文=2个字符,其它都是1个字符,包括emoji都是一个字符长度

发布时间 2023-12-18 15:57:34作者: yoona-lin
// 字符串长度返回:1中文=2个字符,其它都是1个字符
export function getLength(str: any) {
    let strLength = 0;
    for (let i = 0; i < str.length; i++) {
        if (/[\u4e00-\u9fa5]/.test(str[i])) {
            // 判断是否为中文字符,使用 Unicode 范围 [\u4e00-\u9fa5]
            strLength += 2;
        } else {
            strLength += 1;
        }
    }
    const emojiCount = getEmojiCount(str);
    // Emoji长度为2
    return strLength - emojiCount;
}

// 获取字符串Emoji个数
function getEmojiCount(str) {
    const emojiRegex = /\p{Extended_Pictographic}/gu; // 匹配表情符号的正则表达式
    const emojiMatches = str.match(emojiRegex);

    return emojiMatches ? emojiMatches.length : 0;
}