原生JavaScript实现字符串长度截取

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

function cutstr(str, len) {
        var temp;
        var icount = 0;
        var patrn = /[^\x00-\xff]/;
        var strre = "";
        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
                }
                strre += temp
            } else {
                break
            }
        }
        return strre + "..."
    }

 

转载于:https://my.oschina.net/feanlau/blog/879877

你可能感兴趣的:(原生JavaScript实现字符串长度截取)