JS截取指定长度的的字符串(含中文),中文自动按2个字符截取,多出部分用...代替
- /截取字符串,多余的部分用...代替
- function setString(str, len) {
- var strlen = 0;
- var s = "";
- for (var i = 0; i < str.length; i++) {
- if (str.charCodeAt(i) > 128) {
- strlen += 2;
- } else {
- strlen++;
- }
- s += str.charAt(i);
- if (strlen >= len) {
- return s+"...";
- }
- }
- return s;
- }