charAt()方法和charCodeAt()方法用于选取字符串中某一位置上的单个字符。对于检查用户输入的有效性,这两个方法也是非常有用的。charAt()方法具有一个参数:即所选取字符在字符串中的位置。charAt()方法的返回值就是该位置上的字符。字符串中字符的索引位置从0开始,因此,第一个字符的索引是0,第二个字符的索引是1,依此类推。

     charCodeAt()方法与charAt()方法类似,但它并不返回指定位置上的字符本身,而是返回该字符在Unicode字符集中的编码值。计算机只能理解数字,对于计算机来说,所有字符串都是某种编码的数字。当需要使用的是数字编码所代表的字符,而不是使用数字本身时,计算机将根据编码与字符集的内部对应关系,把每一个编码转换为字符集中相应的字符。字符是按顺序进行编码的,例如,字符A的编码是65,字符B的编码是66,依此类推。小写字母从97开始编码,即字母a的编码是97,字母b的编码是98,依此类推。数字字符则是从48开始编码,字符0的编码是48,而字符9的编码是57。用charCodeAt()可以取得大小写字母的Unicode编码值,如:

function charCodeAtTest(n){ 
var str = "0123456789";
  var n;                               
n = str.charCodeAt(n - 1);  
  return(n);                      
}
charCodeAtTest(3);  //返回50

利用charCodeAt()还可以获取多行文本域输入的字符个数进而限制输入的字符个数,实例如下:

 

<SCRIPT language=JavaScript>

<!--

var LastCount =0;

function CountStrByte(Message,Total,Used,Remain){ //字节统计  

var ByteCount = 0;  

var StrValue  = Message.value;  

var StrLength = Message.value.length;  

var MaxValue  = Total.value;

 if(LastCount != StrLength) { // 在此判断,减少循环次数  

   for (i=0;i<StrLength;i++){   

      ByteCount  = (StrValue.charCodeAt(i)<=256) ? ByteCount + 1 : ByteCount + 2;      

      if (ByteCount>MaxValue) {      

          Message.value = StrValue.substring(0,i);    

         alert("评论内容最多不能超过 " +MaxValue+ " 个字节!\n注意:一个汉字为两字节。");         

         ByteCount = MaxValue;         

         break;      

       }  

  }   

  Used.value = ByteCount;    

  Remain.value = MaxValue - ByteCount;   

  LastCount = StrLength;  

 }

}

//-->

</SCRIPT>

<table>

 <form name="form1">
        <tr>
          <td width="23%" height="22" align="right" class="font2">评论人昵称:</td>
          <td width="77%" height="22" align="left"><input name="评论人昵称" type="text" class="textbox" >    </table>

 其中ByteCount  = (StrValue.charCodeAt(i)<=256) ? ByteCount + 1 : ByteCount + 2;判断输入的是否为汉字,如果charCodeAt(i)<=256既不是汉字,字节数加1,否则位汉字,字节数加2.以此来计算文本域中的总字节数。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2021-12-08
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-19
  • 2021-07-14
  • 2022-12-23
  • 2021-06-16
  • 2022-02-26
  • 2022-12-23
  • 2021-10-16
相关资源
相似解决方案