Truncating the middle portion of a string in javascript
When it comes to truncating text in HTML/CSS, most developers are familiar with the simple CSS styling that limits the text to a specific width, such as 250px. However, what if you need to truncate the middle portion of a long string, allowing you to display both the beginning and end sections? In this article, we’ll explore a JavaScript function that efficiently handles this task, providing a clear solution for improved readability. Let’s dive in!
The TruncateString Function: To truncate the middle portion of a string, we can employ the following JavaScript function:
function truncateString(str, firstCharCount = str.length, endCharCount = 0, dotCount = 3) {
if (str.length <= firstCharCount + endCharCount) {
return str; // No truncation needed
}
const firstPortion = str.slice(0, firstCharCount);
const endPortion = str.slice(-endCharCount);
const dots = '.'.repeat(dotCount);
return `${firstPortion}${dots}${endPortion}`;
}Using the Function: The truncateString function accepts four parameters:
str: The string to be truncated.firstCharCount: The number of characters to be shown in the first portion. (Defaults to the length of the input string)endCharCount: The number of characters to be shown in the end portion. (Defaults to 0)dotCount: The count of dots to be placed between the first and end portions. (Defaults to 3)
Examples of Usage: Let’s consider the input example:
const longString = "Doc22302 created by user U1293.pdf";Using the truncateString function, we can achieve different results based on our requirements:
Get Johnu Marattil’s stories in your inbox
Join Medium for free to get updates from this writer.
Truncate the string, showing a portion of the beginning and end:
truncateString(longString);
// Output: "Doc22302 created by user U1293.pdf…"Truncate the string, displaying only the first 8 characters:
truncateString(longString, 8);
// Output: "Doc22302…"Truncate the string, showing 8 characters at the beginning and 3 characters at the end:
truncateString(longString, 8, 3);
// Output: "Doc22302…pdf"Truncate the string, revealing 8 characters at the beginning, 3 characters at the end, and adding 5 dots in between:
truncateString(longString, 8, 9, 2);
// Output: "Doc22302..U1293.pdf"Conclusion: By leveraging the truncateString function provided in this article, developers can easily truncate the middle portion of a string, allowing the display of the first and end sections. Whether you need a simple truncation or a more customized approach with varying dot counts, this function provides a versatile solution. Enhance the readability of your strings today!






