Search code examples
javascripthtmltypescripttrimsubstr

typescript: trim the rest of the text after a specific number of characters


I want to limit text into 15 characters and if it exceeds, the rest of the text should be ...

How do you do that?

I am using this

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

but instead, it removed the first 15 characters


Solution

  • if(txt.length >= 15) {
      txt = txt.substring(0, 15) + '...';
    }
    

    OR, if the you still want just 15 characters to be displayed:

    if(txt.length >= 15) {
      txt = txt.substring(0, 12) + '...';
    }