I wastry to add three dots after 130 characters of string which grabbed from a DIV through the JavaScript innerHTML method. Inside the innerHTML may have more tags and attributes which need to skip while counting. Also need to keep and re-assign the truncated HTML into the same DIV after the operation completed.
Here is some sample input string and expected outputs -
Input 1:
<p>There are many <i>variations</i> of passages of <b>Lorem Ipsum</b> available, but the majority have suffered alteration in some form, by injected humour, or randomised words that don't look even slightly believable.</p> Output 1:
<p>There are many <i>variations</i> of passages of <b>Lorem Ipsum</b> available, but the majority have suffered alteration in some form, by injecte...</p> input 2:
<p><span class="header3">There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words that don't look even slightly believable.</span></p> output 2:
<p><span class="header3">There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injecte...</span></p> Input 3:
<h4><span class="santral-pullquote-32"><span class="body-regular">There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words that don't look even slightly believable.</span></span></h4> Output 3:
<h4><span class="santral-pullquote-32"><span class="body-regular">There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injecte...</span></span></h4> Using the following function Input type 1 is only working but not others:
function cutString = (str) => { let stringCount = 0; let keepCounting = true; let ans = ''; let openTags = []; for (let i = 0; i < str.length; i++) { if (str[i] == "<") { keepCounting = false; if (str[i + 1] != `/`) openTags.push(str[i + 1]) continue; } if (str[i] == ">") { keepCounting = true; if (str[i - 2] == `/`) openTags.splice(openTags.indexOf(str[i - 2]), 1) continue; } if (keepCounting) stringCount++ if (stringCount == 131) { ans = str.slice(0, i); break; } } openTags.forEach(tag => ans = ans + `…</${tag}>`); return ans; } I'm using pure JavaScript (no jQuery). Any help would be greatly appreciated! Thanks in advance.