Last Updated: Oct. 2023
javascript1function truncateString(str, maxLength) { 2 if (str.length > maxLength) { 3 return str.slice(0, maxLength) + '...'; 4 } else { 5 return str; 6 } 7}
Here's an example of how you can use this function:
javascript1let truncatedString = truncateString("Lorem ipsum dolor sit amet", 10); 2console.log(truncatedString); // Outputs: "Lorem ipsu..." 3
This function takes two arguments:
str:
The input string that you want to truncate.
maxLength:
The maximum length the string should be after truncation.
If the length of str
is greater than maxLength
, it will truncate the string and add '...' at the end. Otherwise, it will return the original string.