Truncating a String in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string as the first argument and a number as the second argument.

Our function is supposed to fulfill these three tasks −

  • Truncate the string (first argument) if it is longer than the given maximum string length (second argument) and return the truncated string with a ... ending.

  • The inserted three dots at the end should also add to the string length.

  • However, if the given maximum string length is less than or equal to 3, then the addition of the three dots should not add to the string length in determining the truncated string.

Example

The code for this will be −

const str1 = 'This is an example string';
const str2 = 'abc';
const truncate = (str, len) => {
   if (str.length > len) {
      if (len <= 3) {
         return str.slice(0, len - 3) + "...";
      }
      else {
         return str.slice(0, len) + "...";
      };
   }
   else {
      return str;
   };
};
console.log(truncate(str1, 5));
console.log(truncate(str2, 3));

Output

And the output in the console will be −

This ...
abc
raja
Published on 23-Nov-2020 09:48:24
Advertisements