Posted in Javascript onApril 17, 2013
<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; }
js substr支持中文截取函数代码(中文是双字节)
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@