Ellipsis in the middle of a text (Mac style)

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

    This will give you a little more control over the position of the ellipsis and the placeholder text:

    function ellipsis(str, maxLength, ellipsisLocationPercentage,placeholder) {
        /*
        ARGUMENTS:
        str - the string you want to maninpulate
        maxLength -  max number of characters allowed in return string
        ellipsisLocationPercentage (optional) - How far (percentage wise) into the return string you want the ellipses to be placed
            Examples:
            .85 : This is a very long string. This is a very long string. This is a very long string. This is a ver[...]very long string.
            .25 : This is a very long string. [...]g. This is a very long string. This is a very long string. This is a very long string.
        placeholder (optional) - this will be used to replace the removed substring. Suggestions : '...', '[..]', '[ ... ]', etc....
        */
        if(ellipsisLocationPercentage == null || isNaN(ellipsisLocationPercentage) || ellipsisLocationPercentage >= 1 || ellipsisLocationPercentage <= 0){
            //we've got null or bad data.. default to something fun, like 85% (that's fun, right??)
            ellipsisLocationPercentage = .85;
        }
        if(placeholder == null || placeholder ==""){
            placeholder = "[...]";
        }
    
        if (str.length > (maxLength-placeholder.length)) {
            //get the end of the string
            var beginning = str.substr(0, (maxLength - placeholder.length)*ellipsisLocationPercentage );
            var end = str.substr(str.length-(maxLength - placeholder.length) * (1-ellipsisLocationPercentage));
            return beginning + placeholder + end;
        }
        return str;
    }
    

    You can call this function by calling:

    ellipsis("This is a very long string. Be Scared!!!!", 8);//uses default values
    ellipsis("This is a very long string. Be Scared!!!!", 8,.5);//puts ellipsis at half way point
    ellipsis("This is a very long string. Be Scared!!!!", 8,.75,'<..>');//puts ellipsis at 75% of the way into the string and uses '<..>' as the placeholder
    

提交回复
热议问题