js?字符串中文下對(duì)齊問題解析
更新時(shí)間:2023年07月24日 10:30:37 作者:點(diǎn)墨
這篇文章主要為大家介紹了js字符串含中文下對(duì)齊問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
問題
在中文下對(duì)齊字符串會(huì)出現(xiàn)問題,原因是中文字符占兩個(gè)字節(jié),如下所示
let val = [
{
title:"錯(cuò)嫁豪門:萌娃集合,把渣爹搞破產(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:"錯(cuò)嫁豪門:萌娃集合,把渣爹搞破產(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 字符串中文下對(duì)齊問題解析的詳細(xì)內(nèi)容,更多關(guān)于js 字符串含中文下對(duì)齊的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
原生js實(shí)現(xiàn)鼠標(biāo)滑過播放音符方法詳解
本文使用原生js的AudioContext接口實(shí)現(xiàn)一個(gè)劃過菜單播放天空之城的鼠標(biāo)特效,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
基于JavaScript ES新特性let與const關(guān)鍵字
這篇文章主要介紹了基于JavaScript ES新特性let與const關(guān)鍵字,let是ECMAScript 2015新增的一個(gè)關(guān)鍵字,用于聲明變量,const關(guān)鍵字用于聲明一個(gè)常量,更多詳細(xì)內(nèi)容,請(qǐng)需要的小伙伴參考下面文章的介紹,希望對(duì)你有所幫助2021-12-12
JS數(shù)組方法some、every和find的使用詳情
這篇文章 要給大家介紹的是JS數(shù)組方法some、every和find的使用的一些相關(guān)資料,感興趣的小伙伴一起來學(xué)習(xí)吧2021-09-09

