Replace the end of the text when it is overflowed with three dots with Javascript

In this tutorial, we will learn how to replace the end of the text when it is overflowed with three dots with Javascript. But if you want to do that by CSS, please read the article Replace the end of the text when it is overflowed with three dots by CSS

Example, we will hide the rest of this text when it over 150 characters:

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia

First, write a function like this:

  function truncateText(text){
  	const limit = 150;
    if (text.length > limit) return `${text.slice(0, limit)}...`;
    return text;
  };


Usage:

 const inputText = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia";
 const outputText = truncateText(inputText);


Result:

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore...

The slice method extracts a section of a string and returns it as a new string, without modifying the original string
Syntax: string.slice(beginIndex, endIndex)


© 2019 4codev

Created with love by Sil.