UNPKG

html-truncate-ts

Version:

TypeScript library for truncating HTML strings while preserving HTML tags and structure

79 lines 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.truncate = void 0; const truncate_helpers_1 = require('./truncate.helpers.cjs'); const truncate_const_1 = require('./truncate.const.cjs'); const truncate = (string, maxLength, options) => { const DEFAULT_SLOP = 10 > maxLength ? maxLength : 10; const items = []; let total = 0; let content = truncate_const_1.EMPTY_STRING; let matches; let result; let index; let tag; let selfClose; options = options || truncate_const_1.EMPTY_OBJECT; options.ellipsis = undefined !== options.ellipsis ? options.ellipsis : truncate_const_1.DEFAULT_TRUNCATE_SYMBOL; options.truncateLastWord = undefined !== options.truncateLastWord ? options.truncateLastWord : true; options.slop = undefined !== options.slop ? options.slop : DEFAULT_SLOP; while ((matches = truncate_const_1.HTML_TAG_REGEX.exec(string))) { result = matches[0]; index = matches.index; if (total + index > maxLength) { content += string.substring(0, (0, truncate_helpers_1.getEndPosition)(string, maxLength, total, index, options)); break; } else { total += index; content += string.substring(0, index); } if ('/' === result[1]) { items.pop(); selfClose = null; } else { selfClose = truncate_const_1.SELF_CLOSE_REGEX.exec(result); if (!selfClose) { tag = (0, truncate_helpers_1.getTag)(result); items.push(tag); } } if (selfClose) { content += selfClose[0]; } else { content += result; } string = string.substring(index + result.length); } if (total >= maxLength) { } else { matches = truncate_const_1.URL_REGEX.exec(string); if (!matches || matches.index >= maxLength) { content += string.substring(0, (0, truncate_helpers_1.getEndPosition)(string, maxLength, total, undefined, options)); } else { while (matches) { result = matches[0]; index = matches.index; content += string.substring(0, index + result.length - total); string = string.substring(index + result.length); matches = truncate_const_1.URL_REGEX.exec(string); } } } if (string.length > maxLength - total && options.ellipsis) { content += options.ellipsis; } content += (0, truncate_helpers_1.dumpCloseTag)(items); if (!options.keepImageTag) { content = (0, truncate_helpers_1.removeImageTag)(content); } return content; }; exports.truncate = truncate; //# sourceMappingURL=truncate.js.map