Issue
I use a text editor that will generate a html code and I save in database that html code. On another page I want to display first 100 characters only, but I don't want to count the html tags.
For example I have this html code saved in db:
<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to strip to 100 characters</span></p>
<p>Can be splited <b>between</b> multiple divs.
Here is some more text to be longer <p>
If I substring as usual in javascript it will produce something like this:
<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to s
And this also broke the html code.
What I want is to have like this:
<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to strip to 100 characters</span></p>
<p>Can be splited <b>between</b> multiple divs.
H<p>
I am using angular 4 for this project. So any idea using JS, angular, CSS, HTML or on the backend I have node.js will be helpfull.
Solution
On the frontend, you can do somethign like that :
var div=document.createElement("div");
div.innerHTML='<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>';
var excerpt=div.innerText.substring(0,100);
console.log(excerpt)
Where excerpt are the 100 first characters.
Edit if you want to keep the html tags check this:
var count = 0;
function strip(el, max) {
var children = Array.prototype.slice.call(el.childNodes);
children.forEach((node) => {
if (node instanceof Text) {
var newCount = count + node.textContent.length;
var diff = newCount - max;
if (diff > 0)
node.textContent = node.textContent.substring(0, node.textContent.length - diff);
count += node.textContent.length;
} else if (node instanceof HTMLElement) {
if (count >= max)
node.remove(); // remove unnecessary tags
else
strip(node, max); // do recursively
}
})
}
var div = document.createElement("div");
div.innerHTML = '<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>'
var clone = div.cloneNode(true)
strip(clone, 100)
document.write("<h2>Original</h2>");
document.write(div.innerHTML);
document.write("<h2>Stripped</h2>");
document.write(clone.innerHTML);
Note that the strip function will modify an existing HTMLElement, that's why I cloned it.
If you want to do this on the server side, you can use a dom parser for nodejs and use the same approach.
Answered By - n00dl3
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.