js 小工具-- 按长度截取字符串

Posted on   豌豆娃  阅读(312)  评论(0编辑  收藏  举报
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function cutstr(str,len){
       var temp;
       var icount = 0;
       var stren = "";
       //这段正则表示匹配所有汉字以及全角字符
       var patrn = /[^\x00-\xff]/;
       if (len >= str.length) {
           return str;
       }
       for(var i=0; i<str.length; i++) {
           if (icount< len-1) {
               temp = str.substr(i,1);
               if (patrn.exec(temp) == null) {
                   icount = icount + 1 ;
               }else{
                   icount = icount + 2 ;
               }
               stren += temp;
           }else{
               break;
           }
       }
       return stren + '...';
   }
   </script>

 

努力加载评论中...

Copyright © 2025 豌豆娃
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示