javascript - 如何在没有标签的情况下仅显示 HTML 代码中的前 x 个字符

标签 javascript html css angular

我使用一个文本编辑器来生成 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/

相关文章:

javascript - 在 HTML 文本区域中打印 PHP 变量

html - 跨浏览器响应折叠表

javascript - 使用 PHP 从 JavaScript 程序中的对象文字中提取数据

javascript - 将元素插入 DOM,基于时间戳的位置

javascript - 找到我在 android 上的 phonegap 中遇到的 javascript 错误

javascript - 在 Azure 移动服务上使用服务器端脚本修改响应

php - 如何将json值数据库转换成html

html - 如何让 div、header、container 等覆盖视口(viewport)

css - 哪个类包含 Bootstraps 折叠菜单样式

javascript - 从父级溢出 :scroll 中弹出子级