Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[小白提问] 为什么中文字符算2个长度,而英文字符算1个长度? #1647

Open
loganylwu opened this issue Nov 14, 2023 · 3 comments
Assignees

Comments

@loganylwu
Copy link

tdesign-common 版本

重现链接

No response

重现步骤

export function getCharacterLength(str: string, maxCharacter?: number) {
const hasMaxCharacter = isNumber(maxCharacter);
if (!str || str.length === 0) {
if (hasMaxCharacter) {
return {
length: 0,
characters: str,
};
}
return 0;
}
let len = 0;
for (let i = 0; i < str.length; i++) {
let currentStringLength = 0;
if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
currentStringLength = 2;
} else {
currentStringLength = 1;
}
if (hasMaxCharacter && len + currentStringLength > maxCharacter) {
return {
length: len,
characters: str.slice(0, i),
};
}
len += currentStringLength;
}
if (hasMaxCharacter) {
return {
length: len,
characters: str,
};
}
return len;
}

阅读源代码一直很奇怪,为什么不使用 String.length方法来判断长度,而是特意判断了英文中文,这里面的深意是?

期望结果

No response

实际结果

No response

框架版本

No response

浏览器版本

No response

系统版本

No response

Node版本

No response

补充说明

No response

Copy link

👋 @loganylwu,感谢给 TDesign 提出了 issue。
请根据 issue 模版确保背景信息的完善,我们将调查并尽快回复你。

Copy link

♥️ 有劳 @xiaosansiji 尽快确认问题。
确认有效后将下一步计划和可能需要的时间回复给 @loganylwu

@algerkong
Copy link

这里获取的是字节长度,英文字母是一个字节,中文一个字是占用两个字节

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants