How to Truncate string using Java Script

To do that we need to use the substring() method.


Eg:



let string = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur.";
console.log(string.length > 10 ? string.substring(0, 10) + "..." : string);
//Lorem ipsu...


Code explanation:
  • Check the length of the string.
  • If its grated that 10 we use the subString method
           (more on it here) to take the first 10 letter and append "..." at the end.
  • Else we return the full string
That's how you can do string truncate in js.

Comments