我使用一个文本编辑器来生成 html 代码,并将该 html 代码保存在数据库中。 在另一个页面上,我只想显示前 100 个字符,但我不想计算 html 标签。
例如,我将以下 html 代码保存在数据库中:
<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>
如果我像往常一样在 javascript 中进行子字符串化,它将产生如下内容:
<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to s
这也破坏了 html 代码。
我想要的是这样的:
<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>
我在这个元素中使用 Angular 4。因此,任何使用 JS、Angular、CSS、HTML 或在后端使用 Node.js 的想法都会有所帮助。
最佳答案
在前端,你可以做这样的事情:
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)
其中摘录
是前 100 个字符。
编辑 如果你想保留 html 标签,请检查以下内容:
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);
请注意,strip
函数将修改现有的 HTMLElement,这就是我克隆它的原因。
如果你想在服务器端执行此操作,可以使用 Nodejs 的 dom 解析器并使用相同的方法。
关于javascript - 如何在没有标签的情况下仅显示 HTML 代码中的前 x 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43674530/