使用JS给超长文字添加省略号

function shortLabel(label, maxLen)
{
        if (label.length == 0 || maxLen <= 0)
                return label;
        var half = Math.floor(maxLen/2);
        var len = 0;
        var preSection = 0;
        var needPreCut = false;
        var lastPos = 0;
        var rt;
        var i = 0, j =0;
        for (i = 0; i < label.length; i ++) {
                // let UpperCase hold 2 length
                if(label.charCodeAt(i) > 128 || (label.charCodeAt(i) >= 65 && label.charCodeAt(i) <= 90)) {
                        len += 2;
                } else {
                        len += 1;
                }
                if ((len > half) && (preSection == 0))
                        preSection = i;
                if (len > maxLen) {
                        needPreCut = true;
                        break;
                }
        }

        if (!needPreCut)
                return label;
        else
                rt = label.substr(0, preSection) + '...';

        len = 0;
        for (j = (label.length - 1); j >= 0; j--) {
                if(label.charCodeAt(j) > 128 || (label.charCodeAt(i) >= 65 && label.charCodeAt(i) <= 90)) {
                        len += 2;
                } else {
                        len += 1;
                }
                if ((len > half) && (lastPos == 0)) {
                        lastPos = j + 1;
                        break;
                }
        }

        return rt += label.substr(lastPos, label.length);
}

猜你喜欢

转载自socol.iteye.com/blog/1545853