JS - 实现全角字符转半角字符处理

需求:将全角字符串 " text001" 转换成半角字符串 " text001 "

var str = "text001";
var len = str.length
var newStr = ''
for (var i = 0; i < len; i++) {
    var code = str.charCodeAt(i)
    if (code >= 65281 && code <= 65373) {
        var d = str.charCodeAt(i) - 65248
        newStr += String.fromCharCode(d)
    } else if (code === 12288) {
        var de = str.charCodeAt(i) - 12288 + 32
        newStr += String.fromCharCode(de)
    } else {
        newStr += str.charAt(i)
    }
}
console.log(newStr)

 

posted @ 2021-03-16 11:16  宸晓闹儿06  阅读(477)  评论(0编辑  收藏  举报