html-truncate-ts
Version:
TypeScript library for truncating HTML strings while preserving HTML tags and structure
67 lines • 2.38 kB
JavaScript
import { EXCLUDE_TAGS, IMAGE_TAG_REGEX, WORD_BREAK_REGEX, } from './truncate.const.js';
export const removeImageTag = (string) => {
const match = 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);
};
export const dumpCloseTag = (tags) => {
let html = '';
tags.reverse().forEach((tag) => {
if (-1 === EXCLUDE_TAGS.indexOf(tag)) {
html += '</' + tag + '>';
}
});
return html;
};
export 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);
};
export 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 = 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;
};
//# sourceMappingURL=truncate.helpers.js.map