Ellipsis in the middle of a text (Mac style)

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

    Another stab:

    function truncate( str, max, sep ) {
        max = max || 10;
        var len = str.length;
        if(len > max){
            sep = sep || "...";
            var seplen = sep.length;
            if(seplen > max) { return str.substr(len - max) }
    
            var n = -0.5 * (max - len - seplen);
            var center = len/2;
            return str.substr(0, center - n) + sep + str.substr(len - center + n);
        }
        return str;
    }
    
    console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults) 
    console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters) 
    console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator) 
    

提交回复
热议问题