Dee Caulcrick's Blog

Computer Science & Stuff

picture of dee
Snippet

truncateString()

javascript
function truncateString(str, maxLength) { if (str.length > maxLength) { return str.slice(0, maxLength) + "..."; } else { return str; } }

Here's an example of how you can use this function:

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

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.