|
@@ -196,16 +196,34 @@ function padString(str,width) {
|
|
|
width = width || 21 // 目标宽度为21个单位
|
|
|
spaceChar = " " // 占位符
|
|
|
// 计算字符串的宽度
|
|
|
+ const charWidth = {
|
|
|
+ 'space': 1, // 空格占用1个单位
|
|
|
+ 'zh': 2, // 汉字占用2个单位
|
|
|
+ 'en': 1, // 英文字母占用1个单位
|
|
|
+ 'other': 1 // 其他字符(如标点符号)占用1个单位
|
|
|
+ };
|
|
|
let strWidth = 0;
|
|
|
console.log(str)
|
|
|
+ // 遍历文本中的每个字符
|
|
|
for (let char of str) {
|
|
|
- // 判断字符是否为中文
|
|
|
- if (char.match(/[\u4e00-\u9fa5]/)) {
|
|
|
- strWidth += 2; // 中文字符占4个单位
|
|
|
+ if (/\s/.test(char)) {
|
|
|
+ strWidth += charWidth.space; // 空格
|
|
|
+ } else if (/[\u4e00-\u9fa5]/.test(char)) {
|
|
|
+ strWidth += charWidth.zh; // 汉字
|
|
|
+ } else if (/[a-zA-Z]/.test(char)) {
|
|
|
+ strWidth += charWidth.en; // 英文字母
|
|
|
} else {
|
|
|
- strWidth += 1; // 英文字符占1个单位
|
|
|
+ strWidth += charWidth.other; // 其他字符
|
|
|
}
|
|
|
}
|
|
|
+ // for (let char of str) {
|
|
|
+ // // 判断字符是否为中文
|
|
|
+ // if (char.match(/[\u4e00-\u9fa5]/)) {
|
|
|
+ // strWidth += 2; // 中文字符占4个单位
|
|
|
+ // } else {
|
|
|
+ // strWidth += 1; // 英文字符占1个单位
|
|
|
+ // }
|
|
|
+ // }
|
|
|
|
|
|
const totalPadding = width - strWidth;
|
|
|
// 如果已经达到或超过目标宽度,直接返回原字符串
|