Length Fetch string Lengths
The code is as follows |
Copy Code |
<script type= "Text/javascript" > var str= "string byte length"; alert (str.length); </script> |
In Chinese and English, one character is equivalent to 2 characters
Example 1
The code is as follows |
Copy Code |
<script type= "Text/javascript" > A Chinese character is equivalent to 2 characters function Get_length (s) { var char_length = 0; for (var i = 0; i < s.length; i++) { var Son_char = S.charat (i); encodeURI (Son_char). length > 2? Char_length + + 1:char_length + + 0.5; } return char_length; } function Cut_str (STBR, Len) { var char_length = 0; for (var i = 0; i < str.length; i++) { var son_str = Str.charat (i); encodeURI (SON_STR). length > 2? Char_length + + 1:char_length + + 0.5; if (char_length >= len) { var Sub_len = Char_length = = Len? I+1:I; Return str.substr (0, Sub_len); Break } } } Intercept 15 Words (30 characters) CUT_STR (' AA ah ah ah ah ah oh ah ah ah ah K's AH yes ', 15); </script> |
Example 2
The code is as follows |
Copy Code |
var jmz = {}; Jmz. GetLength = function (str) { <summary> get 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.charcodeat (i); if (charcode >= 0 && charcode <= 128) Reallength + = 1; else Reallength = 2; } return reallength; }; Execute code: Alert (JMZ. GetLength (' Test test Ceshiceshi '); |
Example 3
The two-byte character length is automatically computed as 2, and the character is taken as a single byte, as 2 is 1 characters or two letters, and 1 is a Chinese character or letter.
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" > <title></title>
<body> <div id= ' jsdiv ' style= "border:1px solid #ccc" ></div> <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 (Getstractuallen (STR1)); Alert (GETINTERCEPTEDSTR (str1,25)); </script> </body>
|