Ellipsis in the middle of a text (Mac style)

后端 未结 15 2245
长情又很酷
长情又很酷 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:27

    Here's an elegant solution:

    function truncateMiddle(word) {
        const tooLongChars = 15; // arbitrary
    
        if (word.length < tooLongChars) {
            return word;
        }
    
        const ellipsis = '...';
        const charsOnEitherSide = Math.floor(tooLongChars / 2) - ellipsis.length;
    
        return word.slice(0, charsOnEitherSide) + ellipsis + word.slice(-charsOnEitherSide);
    }
    

提交回复
热议问题