问题
在中文下对齐字符串会出现问题,原因是中文字符占两个字节,如下所示
let val = [
{
title:"错嫁豪门:萌娃集合,把渣爹搞破产",
author:"左暮颜傅寒苍"
},
{
title:"惊!未婚女星竟被萌娃追着叫妈",
author:"大雪无声"
}
]
function test(){
for(let i=0;i<val.length;i++){
let title = alignStr(val[i].title,{len:80});
let author = alignStr(val[i].author,{len:40});
console.log(title + author);
}
}
test();
解决
使用正则替换,将中文字符转换为英文字符,再进行处理
function alignStr(strVal, { len, padChar = " ", shouldCut = true }) {
if (!len || typeof len != "number") return strVal;
if (!strVal) {
return padChar.repeat(len);
} else {
const strLen = strVal.replace(/[^\\x00-\\xff]/ig, "aa").length;
const remainLen = len - strLen;
if(remainLen<0){
return shouldCut ? strVal.substring(0, len) : strVal;
}else if(remainLen > 0){
return strVal + padChar.repeat(remainLen);
}else{
return strVal;
}
}
}
效果如下:
let val = [
{
title:"错嫁豪门:萌娃集合,把渣爹搞破产",
author:"左暮颜傅寒苍"
},
{
title:"惊!未婚女星竟被萌娃追着叫妈",
author:"大雪无声"
}
]
function test1(){
for(let i=0;i<val.length;i++){
let title = val[i].title.padEnd(80);
let author = val[i].author.padEnd(40);
console.log(title + author);
}
}
test1();
function alignStr(strVal, { len, padChar = " ", shouldCut = true }) {
if (!len || typeof len != "number") return strVal;
if (!strVal) {
return padChar.repeat(len);
} else {
let newStrVal = strVal;
const strLen = newStrVal.replace(/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/ig, " ").length;
const remainLen = len - strLen;
if(remainLen<0){
return shouldCut ? newStrVal.substring(0, len) : newStrVal;
}else if(remainLen > 0){
return newStrVal + padChar.repeat(remainLen);
}else{
return newStrVal;
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。