博客 / 詳情

返回

js 字符串含中文下對齊

問題

在中文下對齊字符串會出現問題,原因是中文字符佔兩個字節,如下所示

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

user avatar peter-wilson 頭像 tigerandflower 頭像 luguolangren 頭像 zhangxishuo 頭像 frontoldman 頭像 pangsir8983 頭像 vincehua 頭像 codinger 頭像 _6375bdd01b3a4 頭像 yangzw 頭像 sky124380729 頭像 shijingjing_5ab4aa131e343 頭像
13 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.