UNPKG

html-truncate-ts

Version:

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

74 lines 2.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getEndPosition = exports.getTag = exports.dumpCloseTag = exports.removeImageTag = void 0; const truncate_const_1 = require('./truncate.const.cjs'); const removeImageTag = (string) => { const match = truncate_const_1.IMAGE_TAG_REGEX.exec(string); let index, len; if (!match) { return string; } index = match.index; len = match[0].length; return string.substring(0, index) + string.substring(index + len); }; exports.removeImageTag = removeImageTag; const dumpCloseTag = (tags) => { let html = ''; tags.reverse().forEach((tag) => { if (-1 === truncate_const_1.EXCLUDE_TAGS.indexOf(tag)) { html += '</' + tag + '>'; } }); return html; }; exports.dumpCloseTag = dumpCloseTag; const getTag = (string) => { let tail = string.indexOf(' '); if (-1 === tail) { tail = string.indexOf('>'); if (-1 === tail) { throw new Error('HTML tag is not well-formed : ' + string); } } return string.substring(1, tail); }; exports.getTag = getTag; const getEndPosition = (string, maxLength, total, tailPos, options) => { const DEFAULT_SLOP = 10 > maxLength ? maxLength : 10; const { truncateLastWord, slop } = options || {}; const defaultPos = maxLength - total; const isShort = defaultPos < (slop || DEFAULT_SLOP); const slopPos = isShort ? defaultPos : (slop || DEFAULT_SLOP) - 1; const startSlice = isShort ? 0 : defaultPos - (slop || DEFAULT_SLOP); const endSlice = tailPos || defaultPos + (slop || DEFAULT_SLOP); let position = defaultPos, substr, result; if (!truncateLastWord) { substr = string.slice(startSlice, endSlice); if (tailPos && substr.length <= tailPos) { position = substr.length; } else { while ((result = truncate_const_1.WORD_BREAK_REGEX.exec(substr)) !== null) { if (result.index < slopPos) { position = defaultPos - (slopPos - result.index); if (result.index === 0 && defaultPos <= 1) break; } else if (result.index === slopPos) { position = defaultPos; break; } else { position = defaultPos + (result.index - slopPos); break; } } } if (string.charAt(position - 1).match(/\s$/)) position--; } return position; }; exports.getEndPosition = getEndPosition; //# sourceMappingURL=truncate.helpers.js.map