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

typescript:在特定字符数后修剪文本的其余部分

  •  1
  • user8653311  · 技术社区  · 7 年前

    ...

    你是怎么做到的?

    我在用这个

    return txt.substr(15, txt.length);
    

    但是,它删除了前15个字符

    3 回复  |  直到 7 年前
        1
  •  1
  •   scipper    7 年前
    if(txt.length >= 15) {
      txt = txt.substring(0, 15) + '...';
    }
    

    或者,如果您仍然只想显示15个字符:

    if(txt.length >= 15) {
      txt = txt.substring(0, 12) + '...';
    }
    
        2
  •  1
  •   SickFob    7 年前

    也可以使用concat函数。

    if(txt.length >= 15) {
     return txt.substr(0,15).concat('...');
    } else {
     return txt;
    }
    
        3
  •  1
  •   RajeshKdev    7 年前

    下面的 typescript 代码对我有用。,

    let txt = '1234567890FIFTH_REPLACEME';
    return txt.slice(0, 15).concat('...');
    

    JavaScript中的工作示例:

    单击下面的“运行代码段”按钮,然后单击“尝试”按钮查看结果。,

    function myFunction() {
        var str = "1234567890FIFTH_REPLACEME"; 
        var res = str.slice(0, 15).concat('...');
        document.getElementById("demo").innerHTML = res;
        return res;
    }
    <p>Click the button to display the extracted part of the string.</p>
    
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>