有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:

if (string.length > 25) {
  string = string.substring(0, 24) + "...";
}

当前回答

我喜欢使用.slice(),第一个参数是开始索引,第二个是结束索引。介于两者之间的都是你能得到的。

var long = "hello there! Good day to ya."
// hello there! Good day to ya.

var short  = long.slice(0, 5)
// hello

其他回答

注意,这只需要在Firefox中执行。

所有其他浏览器都支持CSS解决方案(参见支持表):

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}

具有讽刺意味的是,我从Mozilla MDC获得了该代码片段。

我不确定这是否算聪明,但它简洁明了:

truncateStringToLength (string, length) {
  return (string.length > length)
    ? `${string.substring(0, length)} &hellip;`
    : string
}

……然后:

truncateStringToLength('Lorem ipsum dolor sit amet, consetetur sadipscing', 20)

这里是我的解决方案与字边界。

let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." let s_split = s.split(/\s+/); let word_count = 0; let result = ""; //1 for(let i = 0; word_count < 100; i++){ word_count += s_split[i].length+1; result += (s_split[i] + " "); } console.log(result); // 2 word_count = 0; result = s_split.reduce((x,y)=>{ word_count+=(y.length+1); if(word_count>=100) return x; else return x+" "+y;}, "").substring(1); console.log(result);

我在谷歌上快速搜索了一下,发现了这个……这对你有用吗?

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
    var bits, i;
    if (STR !== typeof str) {
        return '';
    }
    bits = str.split('');
    if (bits.length > limit) {
        for (i = bits.length - 1; i > -1; --i) {
            if (i > limit) {
                bits.length = i;
            }
            else if (' ' === bits[i]) {
                bits.length = i;
                break;
            }
        }
        bits.push('...');
    }
    return bits.join('');
};
// END: truncate

使用任一lodash的截断

_.truncate('hi-diddly-ho there, neighborino');
// → 'hi-diddly-ho there, neighbo…'

或下划线。字符串截断。

_('Hello world').truncate(5); => 'Hello...'