GeQin

导航

JavaScript 实时 全角转半角

//JavaScript全角字符转半角(参数str为input框输入的内容)
var $fullChar2halfChar = function(str) {
var result = '';
for (var i = 0; i < str.length; i++) {
//获取当前字符的unicode编码
var code = str.charCodeAt(i);
//unicode编码范围是所有的英文字母以及各种字符
if (code >= 65281 && code <= 65373) {
//把全角字符的unicode编码转换为对应半角字符的unicode码
result += String.fromCharCode(str.charCodeAt(i) - 65248);
} else if (code == 12288) {//空格
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
} else {//原字符返回
result += str.charAt(i);
}
}
return result;
}

//DOM元素

<input type="text" id="test">

//script
需引入jquery
$('#test').on('keyup',function(){
let inputValue = $('#test').val();
inputValue = $fullChar2halfChar(inputValue);
$('#test').val(inputValue);
})

posted on 2017-07-07 15:36  GeQin  阅读(361)  评论(0编辑  收藏  举报