JS determines the length of the input string (Chinese characters count as two characters, letters and numbers count as one)
When text is entered, the submission fails due to the length limit of the database table field, so this verification method was thought of.
Without further ado, let’s talk about the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <html>
<head>
<title>js判断输入字符串长度(汉字算两个字符,字母数字算一个)</title>
<style type= "text/css" >
.pbt {
margin-bottom: 10px;
}
.ie6 .pbt .ftid a, .ie7 .pbt .ftid a {
margin-top: 1px;
}
.cl:after {
clear: both;
content: "." ;
display: block;
height: 0;
visibility: hidden;
}
</style>
<script type= "text/javascript" >
function getByteLen(val) {
var len = 0;
for ( var i = 0; i < val.length; i++) {
var a = val.charAt(i);
if (a.match(/[^\x00-\xff]/ig) != null) {
len += 2;
}
else {
len += 1;
}
}
return len;
}
function checkLength(obj) {
var maxChars = 80;
var curr = maxChars - getByteLen(obj.value);
if (curr > 0) {
document.getElementById( "checklen" ).innerHTML = curr.toString();
} else {
document.getElementById( "checklen" ).innerHTML = '0' ;
document.getElementById( "subject" ).readOnly = true;
}
}
</script>
</head>
<body>
<div class = "pbt cl" >
<textarea id= "subject" maxlength= "80" onkeyup= "checkLength(this)" accesskey= "1" tabindex= "11" ></textarea>
<span id= "subjectchk" >还可输入
<strong id= "checklen" style= "color: #FF0000" >80</strong>
个字符
</span>
<span id= "postNameRule" class = "spn_flag_1" style= "display: none" ></span>
</div>
</body>
</html>
|
Copy after login
The above is how js determines the length of the input string. I hope it will be helpful to everyone's learning and learn how to determine the length of the input string.