@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.
34 lines • 1.32 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
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