Sometimes it is necessary to determine whether a character is a Chinese character. For example, when the user enters the content containing Chinese and English, you need to judge whether it exceeds the prescribed length. There are usually two methods to judge with JavaScript.
1. Use a regular expression to judge
Copy code code as follows:
<! Doctype HTML PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" http://www.w3.org/xhtml1/dtddml1-transitationAl.dtd ">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "content-type" content = "text /html; charset = gb2312" /> />
<Title> JS determines whether characters are Chinese characters </Title>
<Style Type = "Text/CSS">
.content {{
width: 350px;
overflow: hidden;
border: 1px solid #ddd;
}
</style>
<script language = "javascript" type = "text/javascript">
Function Checkchinese (obj, value) {
var reg = new regexp ("[// u4e00- // u9fff]+", "g");
if (reg.Test (Val)) {
Alert ("Can't enter Chinese characters!");
var strobj = document.GetelementByid (obj);
strobj.value = "";
Strobj.focus ();
}
}
</script>
</head>
<body>
<div>
<div> Test characters: <input ID = "test" type = "text" onblur = "Checkchinese ('test', this.value)" /> < /div>
</div>
</body>
</html>
2. Judging the range of the UNICode character
The following method is used to statistics the length of the input string. If it is Chinese characters, the strings are 2; otherwise the strings are 1 with 1.
Copy code code as follows:
Function Chkstrlen (STR)
{{
var strlen = 0;
for (var I = 0; I <str.Length; i ++)
{{
if (Str.charCodeat (i)> 255 // If it is Chinese character, the length of the string is plus 2
stren += 2;
else
Strlen ++;
}
Return Strlen;
}