js 字符串长度截取

 1 <script>
 2   function cutstr(str, len) {
 3     var temp,
 4         icount = 0,
 5         patrn = /[^\x00-\xff]/,
 6         strre = "";
 7     for (var i = 0; i < str.length; i++) {
 8         if (icount < len - 1) {
 9             temp = str.substr(i, 1);
10                 if (patrn.exec(temp) == null) {
11                    icount = icount + 1
12             } else {
13                 icount = icount + 2
14             }
15             strre += temp
16             } else {
17             break;
18         }
19     }
20     return strre + "..."
21   }
22   console.log(cutstr('helloWorld', 3))
23 </script>

 

posted @ 2019-05-07 14:49  左耳_fly  阅读(289)  评论(0编辑  收藏  举报