用javascript截断中间的字符串

spr*_*man 8 javascript

任何人都有一个方便的方法来截断中间的字符串?就像是:

truncate ('abcdefghi', 8);
Run Code Online (Sandbox Code Playgroud)

会导致

'abc...hi'
Run Code Online (Sandbox Code Playgroud)

更新:

更完整一点

  • 如果字符串是<= maxLength,则返回字符串
  • 否则,返回一个maxLength字符串的版本,从中间取出一个块,并替换为"...".
  • 计算总数中"..."的三个字符,因此如果maxLength为8,则只能看到原始字符串中的5个字符

mVC*_*Chr 21

这是一种方法来切断字符串substr:

var truncate = function (fullStr, strLen, separator) {
    if (fullStr.length <= strLen) return fullStr;

    separator = separator || '...';

    var sepLen = separator.length,
        charsToShow = strLen - sepLen,
        frontChars = Math.ceil(charsToShow/2),
        backChars = Math.floor(charsToShow/2);

    return fullStr.substr(0, frontChars) + 
           separator + 
           fullStr.substr(fullStr.length - backChars);
};
Run Code Online (Sandbox Code Playgroud)

见例→