Truncate String and Add Ellipsis with JavaScript



In this article, you will learn how to truncate string and add ellipsis with JavaScript.


The substring () is a method of String object and returns the character string from the start to the end position specified in the argument.
Get the string by specifying the argument as shown below.

str.substring(0, 5);

In the above example, the 5th from the beginning of the string is returned.

Truncate string and add ellipsis

Here is a sample that omits the character string to the specified number of characters with substring().
In the sample below, if the character string is 20 characters or more, it is omitted and output with ellipsis added at the end.


<p id="el">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>


const el = document.getElementById('el');
const str = el.textContent;
const len = 20;

if(str.length > len){
    el.textContent = str.substring(0, len)+'...';