通用的字符是半角,全角可能导致一些异常失败。人工输入是不可靠的,因此需要对输入的内容进行格式化转换
判断是否是半角
function checkCharWidth(str) {
const results = [];
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (charCode >= 0xFF00 && charCode <= 0xFFEF) {
// 全角字符值范围
results.push({ char: str[i], type: '全角', code: charCode });
} else if ((charCode > 0x00 && charCode < 0x81) ||
(charCode === 0xf8f0) ||
(charCode > 0xff5e && charCode < 0xffa0) ||
(charCode > 0xfefe && charCode < 0xff00)) {
// 半角字符值范围
results.push({ char: str[i], type: '半角', code: charCode });
} else {
// 其他字符范围, 可能包含特殊全角字符或其他语言字符
results.push({ char: str[i], type: '未知/其他', code: charCode });
}
}
return results;
}
// 示例使用
const exampleStr = 'ABCabc123123';
const charWidthResults = checkCharWidth(exampleStr);
console.log(charWidthResults);
全角字符转换为半角
function toHalfWidth(str) {
return str.replace(/[\uff01-\uff5e]/g, function (ch) {
// 全角字符的Unicode编码范围是0xFF01-0xFF5E
// 半角字符的Unicode编码范围是0x21-0x7E,且两者相差0xFEE0
return String.fromCharCode(ch.charCodeAt(0) - 0xFEE0);
}).replace(/\u3000/g, ' '); // 将全角空格替换为半角空格
}
// 示例使用
const exampleStr = 'ABCabc123123!?';
const halfWidthStr = toHalfWidth(exampleStr);
console.log(halfWidthStr); // 输出: ABCabc123123!?