[Javascript] How to truncate long string to specific length with ellipses?


I have a very long string, I want to truncate the string to specific length and append ellipses at the end. How to do that in Javascript?

1 Answer

3 years ago by

consider you have a long string and you want to truncate the string to 10 characters, below program shows you how to truncate to your desired length and how to append ellipses to it.

let str= 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

let givenLength = 10;

let truncatedStr = str.length > givenLength ? `${str.substring(0, givenLength)}...` : str;

console.log(truncatedStr);

Run here https://onecompiler.com/javascript/3xnpgurxv

3 years ago by Meera