js substr支持中文截取函数代码(中文是双字节)
<script language="JavaScript">
//得到字符总数
function getChars(str) {
var i = 0;
var c = 0.0;
var unicode = 0;
var len = 0;
if (str == null || str == "") {
return 0;
}
len = str.length;
for(i = 0; i < len; i++) {
unicode = str.charCodeAt(i);
if (unicode < 127) { //判断是单字符还是双字符
c += 1;
} else { //chinese
c += 2;
}
}
return c;
}
function sb_strlen(str) {
return getChars(str);
}
//截取字符
function sb_substr(str, startp, endp) {
var i=0; c = 0; unicode=0; rstr = '';
var len = str.length;
var sblen = sb_strlen(str);
if (startp < 0) {
startp = sblen + startp;
}
if (endp < 1) {
endp = sblen + endp;// - ((str.charCodeAt(len-1) < 127) ? 1 : 2);
}
// 寻找起点
for(i = 0; i < len; i++) {
if (c >= startp) {
break;
}
var unicode = str.charCodeAt(i);
if (unicode < 127) {
c += 1;
} else {
c += 2;
}
}
// 开始取
for(i = i; i < len; i++) {
var unicode = str.charCodeAt(i);
if (unicode < 127) {
c += 1;
} else {
c += 2;
}
rstr += str.charAt(i);
if (c >= endp) {
break;
}
}
return rstr;
}
//调用示例:
function getShortFileName(filename) {
short_filename = filename;
if (sb_strlen(short_filename) > 61) {
short_filename = sb_substr(short_filename, 0, 36) + ' ... ' + sb_substr(short_filename, -20);
}
return short_filename;
}
var chara = 'ni你2好1啊!'
js_self = chara.substr(4);
test = sb_substr(chara,4);
alert("js_self:"+js_self+"ext:"+test);
</script>
function mb_strlen(str) {
var len = 0;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
}
return len;
}
function CutStrLength(str,Ilength)
{
var tmp=0;
var len=0;
var okLen=0
for(var i=0;i255)
tmp+=2
else
len+=1
okLen+=1
if(tmp+len==Ilength)
{
return (str.substring(0,okLen));
break;
}
if(tmp+len>Ilength)
{
return (str.substring(0,okLen-1)+"");
break;
}
}
}
function checkFieldLength(fieldName,fieldDesc,fieldLength)
{
var str=document.getElementById(fieldName).value;
var theLen=0;
var teststr='';
for(i=0;i255)
theLen=theLen+2;
else
theLen=theLen+1;
}
document.getElementById('showMsg').innerText=theLen;
if(theLen>fieldLength)
{
document.getElementById('showMsg').innerText=fieldDesc;
//alert(fieldDesc+" 的字段长度超过规定长度!");
//document.getElementById(fieldName).focus();
document.getElementById(fieldName).value=CutStrLength(str,fieldLength);
return false;
}
else
{
return true;
}
}
//-->
已经输入:
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]