<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" xml:lang ="en" lang ="en" >
< head >
< title ></ title >
</ head >
< body >
< div id ='jsdiv' style ="border:1px solid #ccc" ></ div >
< script type ="text/javascript" >
// 得到字符串的真实长度(双字节换算为两个单字节)
function getStrActualLen(sChars)
{
return sChars.replace( / [ ^ /x00 - /xff] / g, " xx " ).length;
}
// 截取固定长度子字符串 sSource为字符串iLen为长度
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 = " 这是一个字符串截取的函数,this is a test! " ;
// alert(getStrActualLen(str1));
alert(getInterceptedStr(str1, 25 ));
</ script >
</ body >
</ html >
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" xml:lang ="en" lang ="en" >
< head >
< title ></ title >
</ head >
< body >
< div id ='jsdiv' style ="border:1px solid #ccc" ></ div >
< script type ="text/javascript" >
// 得到字符串的真实长度(双字节换算为两个单字节)
function getStrActualLen(sChars)
{
return sChars.replace( / [ ^ /x00 - /xff] / g, " xx " ).length;
}
// 截取固定长度子字符串 sSource为字符串iLen为长度
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 = " 这是一个字符串截取的函数,this is a test! " ;
// alert(getStrActualLen(str1));
alert(getInterceptedStr(str1, 25 ));
</ script >
</ body >
</ html >