Logo
Exploring AI and the future of technology, one post at a time.
From deecaulcrick.com

Filed under JavaScript on October 9, 2023

truncateString()

A JavaScript function to truncate a string

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:

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.