1
<script>
2
String.prototype.truncate = function(bytes)
{
3
4
str = this;
5
showstr = "";
6
7
flag = false;
8
9
strleg = string_get_ascii_leg(str);
10
11
if (strleg > bytes)
12
{
13
for (i=0,j=0;i<bytes;i++,j++)
14
{
15
showstr = showstr.concat(str.charAt(j));
16
if (!(str.charCodeAt(i) < 255))//是否是英文字符
17
{
18
i++;
19
}
20
}
21
showstr = showstr.concat("
");
22
}
23
else
24
{
25
showstr = str;
26
}
27
return showstr;
28
}
29
function string_get_ascii_leg(indata)
30

{
31
var i,strleg;
32
33
strleg = 0;
34
for (i=0;i<indata.length;i++)
35
{
36
strleg++;
37
if (indata.charCodeAt(i) > 255)
38
{
39
strleg++;
40
}
41
}
42
43
return strleg;
44
}
45
</script>

2



3

4

5

6

7

8

9

10

11

12



13

14



15

16

17



18

19

20

21


22

23

24



25

26

27

28

29

30



31

32

33

34

35



36

37

38



39

40

41

42

43

44

45

Example:
1
<script>
2
var test = "我們在哪里";
3
alert(test.truncate(6));
4
</script>

2

3

4
