复制代码 代码如下: <BR>//得到字符总数<BR>function getChars(str) {<BR> var i = 0;<BR> var c = 0.0;<BR> var unicode = 0;<BR> var len = 0;<BR> if (str == null || str == "") {<BR> return 0;<BR> }<BR> len = str.length;<BR> for(i = 0; i < len; i++) {<BR> unicode = str.charCodeAt(i);<BR> if (unicode < 127) { //判断是单字符还是双字符<BR> c += 1;<BR> } else { //chinese<BR> c += 2;<BR> }<BR> }<BR> return c;<BR>}<BR>function sb_strlen(str) {<BR> return getChars(str);<BR>}<BR>//截取字符<BR>function sb_substr(str, startp, endp) {<BR> var i=0; c = 0; unicode=0; rstr = '';<BR> var len = str.length;<BR> var sblen = sb_strlen(str);<BR> if (startp < 0) {<BR> startp = sblen + startp;<BR> }<BR> if (endp < 1) {<BR> endp = sblen + endp;// - ((str.charCodeAt(len-1) < 127) ? 1 : 2);<BR> }<BR> // 寻找起点<BR> for(i = 0; i < len; i++) {<BR> if (c >= startp) {<BR> break;<BR> }<BR> var unicode = str.charCodeAt(i);<BR> if (unicode < 127) {<BR> c += 1;<BR> } else {<BR> c += 2;<BR> }<BR> }<BR> // 开始取<BR> for(i = i; i < len; i++) {<BR> var unicode = str.charCodeAt(i);<BR> if (unicode < 127) {<BR> c += 1;<BR> } else {<BR> c += 2;<BR> }<BR> rstr += str.charAt(i);<BR> if (c >= endp) {<BR> break;<BR> }<BR> }<BR> return rstr;<BR>}<BR>//调用示例:<BR>function getShortFileName(filename) {<BR> short_filename = filename;<BR> if (sb_strlen(short_filename) > 61) {<BR> short_filename = sb_substr(short_filename, 0, 36) + ' ... ' + sb_substr(short_filename, -20);<BR> }<BR> return short_filename;<BR>}<BR>var chara = 'ni你2好1啊!'<BR>js_self = chara.substr(4);<BR>test = sb_substr(chara,4);<BR>alert("js_self:"+js_self+"ext:"+test);<BR> 复制代码 代码如下: function mb_strlen(str) { var len = 0; for(var i = 0; i len += 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;i<Ilength;i++) { if(str.charCodeAt(i)>255) 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;i<str.length;i++) { teststr=str.charAt(i); if(str.charCodeAt(i)>255) 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; } } //--> 已经输入: