zoukankan      html  css  js  c++  java
  • JS判断字串字节数,并截取长度

    这是在项目制作中,积累到的一个东西,感觉效果还可以,现在贴上效果:

    那么,在页面上,我们需要检测两个东西,一个就是字节数,一个就是字符数。

    由于数据库中,要求title的长度字节数为200,那么具体的js代码如下:

       /*************************************************************************
            * CodeBy:SCY  CodeDate:2011年3月11日 12:01:16  
            * DESC:主要是用来判断当前输入的字节数,以便做到限制输入标题的长度功能
            *************************************************************************
    */
            
    var matchWords;
            
    function notifyTextLength() {
                
    var inputNum = document.getElementById("txtTitle").value.replace(/[^\x00-\xff]/g, "**").length; //得到输入的字节数
                if (inputNum <= 200) {
                    matchWords 
    = document.getElementById("txtTitle").value.length;
                    document.getElementById(
    "inputedWord").innerHTML = inputNum + "字节," + matchWords + "字符";
                    document.getElementById(
    "inputtingWord").innerHTML = (200 - inputNum) + "字母,"+(Math.round(((200-inputNum)/2)-0.5))+"汉字";
                }
                
    if (inputNum > 200) {
                        document.getElementById(
    "txtTitle").value = document.getElementById("txtTitle").value.substring(0, matchWords);  //如果超过200字节,就截取到200字节
                    }
                   
            }

    其中,matchWords代表的是当字节数小于200的情况下,匹配的字符的个数;inputNum则是输入的字节数。

    当标题输入的字节数大于200的时候,就按照字符个数进行截取。

    html代码如下:

        <input id="txtTitle" type="text" class="inputText" runat="server" onpropertychange="notifyTextLength();" />
            当前已经输入
    <span id="inputedWord" style="color:red"></span> 还可以输入<span id="inputtingWord" style="color:Red;"></span>
  • 相关阅读:
    hadoop中namenode发生故障的处理方法
    开启虚拟机所报的错误:VMware Workstation cannot connect to the virtual machine. Make sure you have rights to run the program, access all directories the program uses, and access all directories for temporary fil
    Hbase的安装与部署(集群版)
    分别用反射、编程接口的方式创建DataFrame
    用Mapreduce求共同好友
    SparkSteaming中直连与receiver两种方式的区别
    privot函数使用
    Ajax无刷新显示
    使用ScriptManager服务器控件前后台数据交互
    数据库知识
  • 原文地址:https://www.cnblogs.com/scy251147/p/2005333.html
Copyright © 2011-2022 走看看