js如何将全角转换为半角?

JavaScript09

js如何将全角转换为半角?,第1张

<script>

function cc() {

var str = document.getElementById('checkcode').value

var result=''

if (str.length<=0) {return false}

for(var i=0i<str.lengthi++)

{

if(str.charCodeAt(i)>125)

{

result += String.fromCharCode(str.charCodeAt(i)-65248)

} else{

result = str

}

}

document.getElementById('checkcode').value = result

}

</script>

<input class="yanzheng" id="checkcode" type="text" onblur="cc()"/>

字母和数字都可以转过来,文本框失去焦点时转换

有个缺点,输入汉字后就会转换成乱码

var str = "中文‘全角’单引号"

str = str.replace("‘", "'").replace("’", "'")

//输出 中文'全角'单引号

alert(str)

怎么老是想着如何去获取键盘码之类的呢!

哎,你转变下思维嘛!

既然你是即时录入,即时判断的话,那非常简单哪!

我假设你的录入文本框是<input id=txt type=text >

//当文本框的内容改变时,自动调用该函数,这时可以即时对文本内容进行

//判断扫描,是否在输入框内有全角字符出现,如果有,则返回真,如果没有返回假,这样就可以判断是否有全角输入啦!

以下正则是把范围规定在:a-z A-Z 0-9_

<script>

function toDBC( sValue )

{

var rValue =""

for(var i=0i<sValue.lengthi++ )

{

chCode = sValue.charCodeAt(i)

if( chCode >= 65248 &&chCode <= 65375 )

{

rValue += String.fromCharCode( chCode - 65248 )

}

else if( chCode == 12288 )

{

rValue += String.fromCharCode( 32 )

}

else

{

rValue += String.fromCharCode( chCode )

}

}

return rValue

}

document.getElementById("txt").onkeyup=function()

{

var sValue =this.value

sValue=sValue.replace(/[\u4e00-\u9fa5]+/g ,"")

if( /[^\w]/.test( sValue ) )

{

sValue = toDBC( sValue )

}

this.value=sValue

}

</script>