Limiting string up to a specified length in JavaScript


Problem

We are required to write a JavaScript function that takes in a string and a number. Our function should return the truncated version of the given string up to the given limit followed by "..." if the result is shorter than the original string otherwise our function should return the same string if nothing was truncated.

Example

Following is the code −

 Live Demo

const str = 'Testing String';
const num = 8;
const limitString = (str = '', num = 1) => {
   const { length: len } = str;
   if(num < len){
      return str.slice(0, num) + '...';
   }else{
      return str;
   };
};
console.log(limitString(str, num));

Output

Following is the console output −

Testing ...

Updated on: 20-Apr-2021

823 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements