js?字符串中文下對齊問題解析
更新時間:2023年07月24日 10:30:37 作者:點墨
這篇文章主要為大家介紹了js字符串含中文下對齊問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
問題
在中文下對齊字符串會出現(xiàn)問題,原因是中文字符占兩個字節(jié),如下所示
let val = [
{
title:"錯嫁豪門:萌娃集合,把渣爹搞破產(chǎn)",
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();
解決
使用正則替換,將中文字符轉(zhuǎn)換為英文字符,再進(jìn)行處理
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:"錯嫁豪門:萌娃集合,把渣爹搞破產(chǎn)",
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;
}
}
}
以上就是js 字符串中文下對齊問題解析的詳細(xì)內(nèi)容,更多關(guān)于js 字符串含中文下對齊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微信小程序中使用javascript 回調(diào)函數(shù)
這篇文章主要介紹了微信小程序中使用javascript 回調(diào)函數(shù)的相關(guān)資料,需要的朋友可以參考下2017-05-05
JS觸摸屏網(wǎng)頁版仿app彈窗型滾動列表選擇器/日期選擇器
這篇文章主要介紹了觸摸屏網(wǎng)頁版仿app彈窗型滾動列表選擇器/日期選擇器的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-10-10
關(guān)于JavaScript?中?if包含逗號表達(dá)式
這篇文章主要介紹了?關(guān)于JavaScript?中?if包含逗號表達(dá)式,有時會看到JavaScript中if判斷里包含英文逗號?“,”,這個是其實是逗號表達(dá)式。在if條件里,只有最后一個表達(dá)式起判斷作用。下面來看看文章的具體介紹吧2021-11-11
arrify 轉(zhuǎn)數(shù)組實現(xiàn)示例源碼解析
這篇文章主要為大家介紹了arrify 轉(zhuǎn)數(shù)組實現(xiàn)示例源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
JavaScript執(zhí)行機(jī)制詳細(xì)介紹
這篇文章主要介紹了JavaScript執(zhí)行機(jī)制,想要搞懂JavaScript執(zhí)行機(jī)制,便與進(jìn)程與線程的概念脫不了干系,下面我們就來看看這JavaScript執(zhí)行機(jī)制的具體介紹吧,需要的朋友可以參考一下2021-12-12

