//str 目标字符串,tarLen 目标所占空格长度(字节长度)
function formatStr(str, tarLen) {
//汉字相当于两个空格的字节,但是页面视觉上一个汉字要比两个空格占地窄一点
console.log('目标空格个数', tarLen)//目标字节数
if (tarLen % 2 !== 0) {
console.log('!!-----目标字节建议为偶数,否则会损失字节精度--------')
}
let len = 0
let newStr = str
if (typeof str != "string") {
console.log('字符串有误', str)
return str
}
len = str.replace(/[^\x00-\xff]/g, "01").length;//关键,把单字节换成01(补成两个字节)slice返回新的字符串,这里替换不会影响原来的str
console.log('第一次字节长度', len, '--newStr', newStr + '==', '--str', str + '==')
if (len >= tarLen) {
//字符串字节数比目标数大,为了避免按照字符串截取时损失字节,这里判断一下截取之后的末位和末位的后一位的字节
console.log('字符串字节数比目标数大或者一样大')
//截取后的末位是单字节 且 末位后的一位也是单字节,则将末位后的一位保留
if (newStr.substr((tarLen / 2) - 1, 1).replace(/[^\x00-\xff]/g, "01").length === 1
&& newStr.substr((tarLen / 2), 1).replace(/[^\x00-\xff]/g, "01").length === 1
) {
newStr = newStr.slice(0, ((tarLen / 2) + 1))
} else {
newStr = newStr.slice(0, tarLen / 2)
}
str = newStr
}
len = str.replace(/[^\x00-\xff]/g, "01").length;//关键,在截取之后再获取一次字符串,把单字节换成01(补成两个字节)slice返回新的字符串,这里替换不会影响原来的str
console.log('第二次字节长度', len, '--newStr', newStr + '==', '--str', str + '==')
if (len < tarLen) {
console.log('补充的空格数', tarLen - len)
let blank = ''
for (let i = 0; i < tarLen - len; i++) {
blank += ' '
}
return newStr += blank
}
return newStr//新的str
}
jquery 统一字符串长度
于 2022-02-18 17:19:58 首次发布