源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JS判断字符串字节数并截取长度的方法

  • 时间:2022-06-17 02:54 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JS判断字符串字节数并截取长度的方法
本文实例讲述了JS判断字符串字节数并截取长度的方法。分享给大家供大家参考,具体如下: 这是在项目制作中,积累到的一个东西,感觉效果还可以,现在贴上效果: [img]http://files.jb51.net/file_images/article/201603/201635120326573.jpg?20162512348[/img] 那么,在页面上,我们需要检测两个东西,一个就是字节数,一个就是字符数。 由于数据库中,要求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>

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/472.htm]JavaScript查找算法技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/462.htm]JavaScript动画特效与技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/439.htm]JavaScript错误与调试技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/297.htm]JavaScript数据结构与算法技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/281.htm]JavaScript遍历算法与技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/119.htm]JavaScript数学运算用法总结[/url]》 希望本文所述对大家JavaScript程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部