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

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

当前回答

聪明的地方:D

//My Huge Huge String let tooHugeToHandle = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).` //Trim Max Length const maxValue = 50 // The barber. const TrimMyString = (string, maxLength, start = 0) => { //Note - `start` is if I want to start after some point of the string if (string.length > maxLength) { let trimmedString = string.substr(start, maxLength) return ( trimmedString.substr( start, Math.min(trimmedString.length, trimmedString.lastIndexOf(' ')) ) + ' ...' ) } return string } console.log(TrimMyString(tooHugeToHandle, maxValue))

其他回答

人们希望用JavaScript而不是CSS来实现这一点是有充分理由的。

在JavaScript中截断为8个字符(包括省略号):

short = long.replace(/(.{7})..+/, "$1…");

or

short = long.replace(/(.{7})..+/, "$1…");

如果你想用css而不是JavaScript;

.textShortDesc { /*Here we have determined the max number of lines.*/
    display: block; /* or inline-block */
    -o-text-overflow: ellipsis; /* Opera < 11*/
    text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
    word-wrap: break-word;
    overflow: hidden;
    max-height: 2em; /*max-height/line-height=rowCount */
    line-height: 1em;
}

Text-overflow:省略号是您需要的属性。有了这个和一个溢出:隐藏在一个特定的宽度,超过它的所有东西将在最后得到三个周期的效果……不要忘记添加空格:nowrap或文本将被放入多行。

.wrap{
  text-overflow: ellipsis
  white-space: nowrap;
  overflow: hidden;
  width:"your desired width";
}
<p class="wrap">The string to be cut</p>

有时文件名是编号的,其中索引可能在开头或结尾。所以我想从弦的中心开始缩短:

function stringTruncateFromCenter(str, maxLength) {
    const midChar = "…";      // character to insert into the center of the result
    var left, right;

    if (str.length <= maxLength) return str;

    // length of beginning part      
    left = Math.ceil(maxLength / 2);

    // start index of ending part   
    right = str.length - Math.floor(maxLength / 2) + 1;   

    return str.substr(0, left) + midChar + str.substring(right);
}

请注意,我在这里使用了UTF-8中超过1个字节的填充字符。

使用任一lodash的截断

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

或下划线。字符串截断。

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