@azizbecha/strkit
Version:
strkit is a utility library offering a collection of essential string functions including validation, case conversion, truncation, and more. Ideal for both JavaScript and TypeScript developers to simplify string operations in their applications.
24 lines • 879 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = truncateMiddle;
/**
* Truncates the middle of a string and replaces it with an ellipsis (...).
*
* @param str - The input string to truncate.
* @param maxLength - The maximum length of the truncated string (default is 10).
* @returns The truncated string with the middle replaced by ellipsis if necessary.
*
* @example
* truncateMiddle("HelloWorld", 5); // Output: "He...ld"
* truncateMiddle("JavaScript", 15); // Output: "JavaScript" (unchanged)
*/
function truncateMiddle(str, maxLength = 10) {
if (str.length <= maxLength) {
return str;
}
const halfLength = Math.floor((maxLength - 3) / 2);
const start = str.slice(0, halfLength);
const end = str.slice(-halfLength);
return `${start}...${end}`;
}
//# sourceMappingURL=truncateMiddle.js.map