I want to truncate a text or line with ellipsis using JavaScript

Dollar Friend picture Dollar Friend · Jan 15, 2011 · Viewed 117.7k times · Source

I'm looking for a simple script which can truncate a string with ellipsis (...)

I want to truncate something like 'this is a very long string' to 'this is a ve...'

I don't want to use CSS or PHP.

Answer

El Ronnoco picture El Ronnoco · Jan 15, 2011
function truncate(input) {
   if (input.length > 5) {
      return input.substring(0, 5) + '...';
   }
   return input;
};

or in ES6

const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;