Skip to content

Instantly share code, notes, and snippets.

@lbj96347
Created February 1, 2012 03:26
Show Gist options
  • Save lbj96347/1714909 to your computer and use it in GitHub Desktop.
Save lbj96347/1714909 to your computer and use it in GitHub Desktop.
JS处理中英文字符
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>hello world</title>
<script src='library/jquery-1.7.min.js' type='text/javascript'></script>
</head>
<body>
<h1>CashLee's Macbook</h1>
<label>判断是否为中文字符,输入英文的时候会提示错误</label>
<input type='text' id='part' width='100px;' />
<button onclick='dealChar();'>check</button>
<!-- 遍历判断 -->
<script>
function dealChar(){
var s = $('#part').val();
for(var i = 0; i < s.length; i++) {
if(s.charCodeAt(i) < 0x4E00 || s.charCodeAt(i) > 0x9FA5) {
alert("輸入非中文,請重新輸入");
break;
}
}
for(var i = 0; i < s.length; i++) {
if( 0x4E00< s.charCodeAt(i) <0x9FA5) {
alert("对的输入了中文");
break;
}
}
}
</script>
<!-- 正则判断 -->
<script language="javascript">
function XN_CheckAllCnText(str)
{
var reg=/[\u4E00-\u9FA5]/g
if (reg.test(str)){alert("含有汉字");}
else{alert("不含有汉字");}
}
</script>
<input type="text" name="test" />
<input type="button" name="testbutton" value="点击我看看" onclick="XN_CheckAllCnText(document.all.test.value)" />
<pre>
中文:/^[\u4E00-\u9FA5]+$/
數字:/^d+$/(是非負整數哦)
字母:/^[a-zA-Z]{1,30}$/(1到30個以字母串)
// 目前在Unicode標準中,漢字的Char Code範圍是[0x4E00, 0x9FA5]
</pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment