HTML Text Trucator
by Felipe Alfaro
HTML
<div id="test">
<h1>Hello World!!</h1>
<p>Some content here.</p>
<br>
<span>Some content here.</span>
</div>
TypeScript
const htmlTextElement = document.getElementById('test');
const rawHTMLText = htmlTextElement.innerHTML;
const regexToFindTagsSring = /(<([^>]+)>)/ig;
const regexToFindSpaces = /^\s*|\s*$|\s*(\r?\n)\s*|(\s)\s+/g;
const htmlText = rawHTMLText.replace(regexToFindSpaces, '');
const pureText = rawHTMLText.replace(regexToFindTagsSring, '').replace(regexToFindSpaces, ' ').trim();
const matchList = htmlText.matchAll(regexToFindTagsSring);
let result = String(pureText).slice(0, 40);
const savedTags: {
[index: number]: string
} = {};
let previousLength = 0;
matchList.forEach((match, iterationIndex) => {
const indexFix = result[match.index + 1] === ' ' ? 1 : 0;
result = result.slice(0, match.index) + match[0] + result.slice(match.index).trim();
});
console.log(pureText);
console.log(htmlText);
console.log(result);
//////Hello World!! Some content here. Some content here.
//////<h1>Hello World!!</h1><p> Some content here. Some content here.