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>
|