Ellipsis in the middle of a text (Mac style)

后端 未结 15 2274
长情又很酷
长情又很酷 2020-11-29 03:04

I need to implement ellipsis (\"...\") in the middle of a text within a resizable element. Here is what it might look like. So,

\"Lorem ipsum do         


        
15条回答
  •  情书的邮戳
    2020-11-29 03:32

    This solution is a mix of the above solutions and puts the last whole word at the end of the shortened text. However in case the last word is longer then a third of the available space it is also shortend from the left. If a dash("-") is found, cut it of there, if not, cut it of anyway.

    function truncate(text, textLimit) {
        if (!text) return text;
        if (textLimit < 1) return string;
        if (text.length < textLimit) return text;
        if (textLimit === 1) return text.substring(0,1) + '...';
        /* extract the last word */
        var lastPart = text.slice( string.lastIndexOf(' ')+1 );
        /* if last word is longer then a third of the max available space
           cut it from the left */
        var lastPartLimit = Math.ceil(textLimit / 3);
        if(lastPart.length > lastPartLimit) {
            var truncatedLastPart = lastPart;
            /* Try to find a dash and cut the last word there */
            var lastDashPart = text.slice( text.lastIndexOf('-')+1 );
            if(lastDashPart.length < lastPartLimit){
                truncatedLastPart = lastDashPart;
            }
            /* If the last part is still to long or not available cut it anyway */
            if(truncatedLastPart.length > lastPartLimit) {
                var lastIndex = lastPart.length - lastPartLimit;
                truncatedLastPart = lastPart.substring( lastIndex );
            }
            lastPart = truncatedLastPart;
        }
        var dots = '... ';
        var firsPartLength = textLimit - lastPart.length - dots.length;
        return text.substring(0, firstPartLength) + dots + lastPart;
    }
    
    console.log( truncate("New York City", 10) ); // Ne... City (max of 10 characters)
    console.log( truncate("New York Kindergarden", 14) ); // Ne...ergarden (max of 14 characters, last word gets cut from the left by a third)
    console.log( truncate("New York Kinder-garden", 14) ); // Ne...garden (max of 14 characters, last word gets cut by the dash from the left)
    

提交回复
热议问题