html-truncate-ts
Version:
TypeScript library for truncating HTML strings while preserving HTML tags and structure
75 lines • 2.6 kB
JavaScript
import { removeImageTag, dumpCloseTag, getTag, getEndPosition, } from './truncate.helpers.js';
import { EMPTY_OBJECT, EMPTY_STRING, DEFAULT_TRUNCATE_SYMBOL, HTML_TAG_REGEX, URL_REGEX, SELF_CLOSE_REGEX, } from './truncate.const.js';
export const truncate = (string, maxLength, options) => {
const DEFAULT_SLOP = 10 > maxLength ? maxLength : 10;
const items = [];
let total = 0;
let content = EMPTY_STRING;
let matches;
let result;
let index;
let tag;
let selfClose;
options = options || EMPTY_OBJECT;
options.ellipsis =
undefined !== options.ellipsis ? options.ellipsis : DEFAULT_TRUNCATE_SYMBOL;
options.truncateLastWord =
undefined !== options.truncateLastWord ? options.truncateLastWord : true;
options.slop = undefined !== options.slop ? options.slop : DEFAULT_SLOP;
while ((matches = HTML_TAG_REGEX.exec(string))) {
result = matches[0];
index = matches.index;
if (total + index > maxLength) {
content += string.substring(0, getEndPosition(string, maxLength, total, index, options));
break;
}
else {
total += index;
content += string.substring(0, index);
}
if ('/' === result[1]) {
items.pop();
selfClose = null;
}
else {
selfClose = SELF_CLOSE_REGEX.exec(result);
if (!selfClose) {
tag = getTag(result);
items.push(tag);
}
}
if (selfClose) {
content += selfClose[0];
}
else {
content += result;
}
string = string.substring(index + result.length);
}
if (total >= maxLength) {
}
else {
matches = URL_REGEX.exec(string);
if (!matches || matches.index >= maxLength) {
content += string.substring(0, 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 = URL_REGEX.exec(string);
}
}
}
if (string.length > maxLength - total && options.ellipsis) {
content += options.ellipsis;
}
content += dumpCloseTag(items);
if (!options.keepImageTag) {
content = removeImageTag(content);
}
return content;
};
//# sourceMappingURL=truncate.js.map