---
title: "JS判断字串字节数，并截取长度"
author: "lkf009"
date: "2013-04-27T11:40:50Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2013-04-27T11:40:50Z"
id: 1855778
url: "https://lkf009.iteye.com/blog/1855778"
---

转自：[http://www.cnblogs.com/scy251147/archive/2011/04/04/2005333.html](http://www.cnblogs.com/scy251147/archive/2011/04/04/2005333.html)

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

![](http://images.cnblogs.com/cnblogs_com/scy251147/%E6%B5%8B%E8%AF%95%E5%AD%97%E7%AC%A6.jpg)

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

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

 

[![复制代码](http://common.cnblogs.com/images/copycode.gif)](/admin/blogs/ "复制代码")

   /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
        * 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 &lt;= 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 &gt; 200) {  
                    document.getElementById("txtTitle").value = document.getElementById("txtTitle").value.substring(0, matchWords);  //如果超过200字节，就截取到200字节  
                }  
                 
        }

[![复制代码](http://common.cnblogs.com/images/copycode.gif)](/admin/blogs/ "复制代码")

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

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

html代码如下：

 

    &lt;input id="txtTitle" type="text" class="inputText" runat="server" onpropertychange="notifyTextLength();" /&gt;  
        当前已经输入&lt;span id="inputedWord" style="color:red"&gt;&lt;/span&gt; 还可以输入&lt;span id="inputtingWord" style="color:Red;"&gt;&lt;/span&gt;