I have a problem where I need to cut off text based on a max length. But the inputted string could be html a la <p>hello</p>. the html tags do not count towards the max length.
for example with this text if the max length was 3 I would need to slice it like so <p>hel. I'm trying to think of a clever way to do this. Wondering if anyone has any ideas while I try to work it out. I have the ability to strip the tags from the text so I have find where in the text I need to stop but the tricky part is find where that text lives in the original string.
UPDATE: Thanks to both comments I was inspired to write this, hopefully it helps anyone else with this problem:
const cutHTMLCharactersByMaxlength = (htmlString: string, maxLength: number) => {
const parent = document.createElement('div');
parent.innerHTML = htmlString;
countHTMLCharactersRecurse(parent, maxLength, 0);
return parent.innerHTML;
}
const countHTMLCharactersRecurse = (node: Node, maxLength: number, count: number) => {
if (node.nodeType === 3) {
if (maxLength === count) {
node.textContent = "";
} else {
count += node.textContent?.length || 0;
if (count > maxLength) {
const diff = count - maxLength;
node.textContent = node.textContent?.slice(0, -1*diff) || "";
count = maxLength;
}
}
return count;
}
const numChildren = node.childNodes.length;
for (let index = 0; index < numChildren; index++) {
count = countHTMLCharactersRecurse(node.childNodes[index], maxLength, count);
}
return count;
}