Here’s a quick JavaScript helper snippet to return a trimmed string based on the calculated maximum length of a string to fit the width of a parent container element.
Written in TypeScript.
/** * Takes a full string and returns a trimmed version to fit within a parent space. * @param fullLengthString The full length string to trim to a parent space. * @param font String representing the font styling of the text (required to calculate text length). * @param maxLengthPixels Max pixel width of the parent space to fit the text into. * @param removeExtraChars The number of extr characters to remove from the trimmed space, if required. (Default: 0) */ private getMaxLengthString(fullLengthString: string, font: string, maxLengthPixels: number, removeExtraChars: number = 0): string { let maxLengthString: string = ""; let canvas = document.createElement("canvas"); let context = canvas.getContext("2d"); context.font = font; for (let i = 0; i < fullLengthString.length; i++) { // Build the string maxLengthString = maxLengthString + fullLengthString.charAt(i); // Test the length of the string let metrics = context.measureText(maxLengthString); if (metrics.width > maxLengthPixels) { // Trim the string to a max length. // The number of characters to remove. let removeChars = 1; // At this point the length is too long, so remove 1 character to get it under. if (removeExtraChars > 0) { removeChars = removeChars + removeExtraChars; } removeChars = removeChars * -1; // To make sure they're sliced from the end. // Remove characters from the string. maxLengthString = maxLengthString.slice(0, removeChars); return maxLengthString; } } // Full string is OK. return maxLengthString; }