代码之家  ›  专栏  ›  技术社区  ›  alex

为什么下面的省略号/截断函数不能将字符串剪切成相同的长度?

  •  -1
  • alex  · 技术社区  · 9 年前

    ... 最后:

    ellipsis (string, threshold) {
      if (string.length > threshold) return string.substring(0, threshold) + '...'
      else return string
    },
    

    ellipsis(string, 35)

    示例字符串:

    123456789012345678901234567890123456789012345678901234567890
    
    4567896 7890456 8904567 
     89456789456789456789456789456789456789456789456789456789456789
    

    结果:

    12345678901234567890123456789012...
    
    4567896 7890456 8904567 
     894567...
    

    正如你所看到的,第二个字符串最后变短了。

    原件:4567896 7890456 8904567 89456789456789456789456789456789456789456789456789456789456789

    89456789456789456789456789456789456789456789456789456789456789

    1 回复  |  直到 9 年前
        1
  •  1
  •   prasanth    9 年前

    replace() 新品

    function ellipsis(string, threshold) {
      if (string.length > threshold) {
        return (string.substring(0, threshold) + '...').replace(/\\n/g,'').trim()
      } else {
        return string
      }
    }
    
    var string1 = '123456789012345678901234567890123456789012345678901234567890';
    console.log(ellipsis(string1, 35))
    
    
    var string2 = '4567896 7890456 8904567  89456789456789456789456789456789456789456789456789456789456789';
    console.log(ellipsis(string2, 35))

    已更新 你可以扩展你的 console.log .它没有任何中断

    enter image description here