js 字符串中文下对齐问题解析
作者:点墨
这篇文章主要为大家介绍了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();
解决
使用正则替换,将中文字符转换为英文字符,再进行处理
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; } } }
以上就是js 字符串中文下对齐问题解析的详细内容,更多关于js 字符串含中文下对齐的资料请关注脚本之家其它相关文章!