作者:yunser
链接:https://www.zhihu.com/question/20463721/answer/297029567
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
// 全角空格为12288,半角空格为32
// 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
// 转换为全角
_toFull(text) {
let tmp = ''
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) === 32) {
tmp = tmp + String.fromCharCode(12288)
} else if (text.charCodeAt(i) < 127) {
tmp = tmp + String.fromCharCode(text.charCodeAt(i) + 65248)
} else {
tmp = tmp + String.fromCharCode(text.charCodeAt(i))
}
}
return tmp
}
// 转换为半角
_toHalf(text) {
let tmp = ''
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) > 65280 && text.charCodeAt(i) < 65375) {
tmp += String.fromCharCode(text.charCodeAt(i) - 65248)
} else if (text.charCodeAt(i) === 12288) {
tmp += String.fromCharCode(32)
} else {
tmp += String.fromCharCode(text.charCodeAt(i))
}
}
return tmp
}