Snippet

truncateString()

javascript
1function 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:

javascript
1let truncatedString = truncateString("Lorem ipsum dolor sit amet", 10); 2console.log(truncatedString); // Outputs: "Lorem ipsu..." 3

Context

This function takes two arguments:

  1. str: The input string that you want to truncate.

  2. 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.