Javascipt Get string True Length (compatible Ie,firefox)

Source: Internet
Author: User

JS has the same length as English. A character is 1 lengths. So here we need to judge for ourselves and get the actual length of the string.
Core code:

  code is as follows copy code
var = {};
Jmz. GetLength = function (str) {
   ///<summary> gets the actual length of the string, Chinese 2, English 1</summary>
    ///<param name= "str" > to get the length of the string </param>
    var reallength = 0, Len = Str.length, charcode =-1;
    for (var i = 0; i < len; i++) {
        charcode = str.c Harcodeat (i);
        if (charcode >= 0 && charcode <= 128) Reallength + = 1;
        Else reallength + + 2;
   }
    return reallength;
};   

Execute code:

The code is as follows Copy Code

Alert (JMZ. GetLength (' Test test Ceshiceshi ');

JS version Get string True length and fixed length string function (compatible Ie,firefox)

The code is as follows Copy Code
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>js version gets string true length and fixed-length string functions (compatible Ie,firefox)
</title>
<body>
<script type= "Text/javascript" >
Gets the true length of the string (two bytes converted to two single-byte)
function Getstractuallen (schars)
{
Return Schars.replace (/[^x00-xff]/g, "xx"). Length;
}
Intercept fixed-length substring ssource for string Ilen length
function Getinterceptedstr (ssource, Ilen)
{
if (Ssource.replace (/[^x00-xff]/g, "xx"). Length <= Ilen)
{
return ssource;
}
var str = "";
var L = 0;
var Schar;
for (var i=0; Schar=ssource.charat (i); i++)
{
str = Schar;
L + = (Schar.match (/[^x00-xff]/)!= null? 2:1);
if (l >= ilen)
{
Break
}
}
return str;
}
var str1= "It is a function of a string intercept, this is a test!";
Alert (GETINTERCEPTEDSTR (str1,29));
</script>
</body>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.