1

问题

在中文下对齐字符串会出现问题,原因是中文字符占两个字节,如下所示

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();

image.png

解决

使用正则替换,将中文字符转换为英文字符,再进行处理

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;
    }
  }
}

image.png


点墨
26 声望3 粉丝

全栈前端开发工程师