function truncateString(str, maxLength) {
if (str.length <= maxLength) {
return str;
}
var ellipsis = '...';
var truncatedLength = maxLength - ellipsis.length;
var leftLength = Math.ceil(truncatedLength / 2);
var rightLength = Math.floor(truncatedLength / 2);
var leftSubstring = str.substring(0, leftLength);
var rightSubstring = str.substring(str.length - rightLength);
return leftSubstring + ellipsis + rightSubstring;
}
EXPLAINED:
The truncateString function takes two parameters: str, which is the original string to be truncated, and maxLength, which is the maximum length of the truncated string (including the ellipsis). If the length of the original string is less than or equal to the maxLength, the function simply returns the original string.
If the length of the original string is greater than the maxLength, the function calculates the lengths of the left and right substrings to be included in the truncated string. The lengths are calculated to be roughly equal, with the left substring potentially having one extra character if the truncatedLength is an odd number.
The function then uses the substring method to extract the appropriate substrings from the original string, and concatenates them with the ellipsis in the middle.
Finally, the truncated string is returned.