在JavaScript中控制全角和半角字符主要涉及到字符编码和字符串处理。全角字符和半角字符的主要区别在于它们占用的显示空间和编码长度不同。全角字符通常用于中文、日文等语言的书写系统,而半角字符则多用于英文和其他西文语言。
\u3000
)32
),
、。
等,
、.
等function isFullWidth(char) {
const code = char.charCodeAt(0);
return (code >= 0x3000 && code <= 0x303F) || // CJK symbols and punctuation
(code >= 0xFF00 && code <= 0xFFEF) || // Halfwidth and Fullwidth Forms
(code >= 0x4E00 && code <= 0x9FFF); // CJK Unified Ideographs
}
function toHalfWidth(str) {
return str.replace(/[\u3000-\u303F\uFF00-\uFFEF\u4E00-\u9FFF]/g, function(ch) {
const code = ch.charCodeAt(0);
if (code >= 0xFF00 && code <= 0xFFEF) {
return String.fromCharCode(code - 0xFEE0);
} else if (code === 0x3000) {
return ' ';
} else {
// 对于其他全角字符,可以根据需要进行处理
return ch;
}
});
}
function toFullWidth(str) {
return str.replace(/[\u0020-\u007E]/g, function(ch) {
const code = ch.charCodeAt(0);
if (code >= 0x20 && code <= 0x7E) {
return String.fromCharCode(code + 0xFEE0);
} else {
return ch;
}
}).replace(/ /g, ' '); // 半角空格转换为全角空格
}
const input = "Hello,世界! 123";
const halfWidth = toHalfWidth(input);
console.log(halfWidth); // "Hello,世界! 123"
const fullWidth = toFullWidth(input);
console.log(fullWidth); // "Hello,世界!123"
通过上述方法,可以在JavaScript中有效地控制和处理全角和半角字符。
领取专属 10元无门槛券
手把手带您无忧上云