React中如何截断HTML文本?

3

我正在尝试将以下HTML截断为5个字符:

<b>Hello</b> how are you today?

我期望得到的结果是:

Hello

但是,我该如何忽略截断中的HTML标签,以免出现以下情况?
<b>He

我正在使用一个HTML解析器,因此在使用后无法截断字符串。这是我的代码,不用说显然不能正常工作!
import React from 'react';
import parse from 'html-react-parser';
import Typography from '@material-ui/core/Typography';


const Message= () => {
  const message= "<b>Hello</b> how are you today?"
  const messageParsed = parse(message);

  return (
          <Typography variant="body2">
            {messageParsed.substr(0, 5)}
          </Typography>
  );
};

export default Message;

什么是正确的方法?

非常感谢,

Katie

4个回答

1
如果您不想按字符大小截断,下面的方法可以帮助您。
  • 对于一行:
p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
  • 对于多行文本(例如:3行)
p {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

或者

p {
  height: 4.5rem;
  line-height: 1.5rem;
  overflow: hidden;
}

如果你想按字符大小截断

div {
  /* <div><p></p></div> */
  width: '50px'; /* equal pixels to characters width */
  overflow: hidden;
}

1
您可以使用Range来保留HTML结构。
要获取指定长度的HTML,请调用下面的htmlToLength(html, length)
您还可以通过调用htmlToNodeWithLength(html, length)来获取DocumentFragment。
该算法的核心是findRangeWithLength(range, length),它从末尾(递归地)缩小range,直到其具有给定的length

function htmlToLength(html, length) {
  const trimmedNode = htmlToNodeWithLength(html, length);

  const container = document.createElement("div");
  container.appendChild(trimmedNode);
  return container.innerHTML;
}

function htmlToNodeWithLength(html, length) {
  // Only for measurement. Never added to DOM.
  const container = document.createElement("div");
  container.innerHTML = html;

  const fullRange = document.createRange();
  fullRange.setStart(container, 0);
  fullRange.setEnd(container, 1);

  const range = findRangeWithLength(fullRange, length);
  return range.cloneContents();
}

function findRangeWithLength(range, length) {
  if (rangeLength(range) < length) return range;

  // Find the childNode with at least length content.
  for (const childNode of range.endContainer.childNodes) {
    range.setEnd(childNode, lastEndOffset(childNode));
    if (rangeLength(range) >= length) {
      return findRangeWithLength(range, length);
    }
  }

  // There are no child nodes long enough. It's a text node.
  const diff = length - rangeLength(range) + range.endOffset;
  range.setEnd(range.endContainer, diff);
  return range;
}

function lastEndOffset(node) {
  return node.childNodes.length || node.textContent.length;
}

function rangeLength(range) {
  return range.toString().length;
}

const html = "<p>No <span></span><b>Hello</b> <i>World</i></p>";
const length = 7;
const trimmedNode = htmlToNodeWithLength(html, length);

document.querySelector(".raw-input").textContent = html;
document.querySelector(".trimmed").appendChild(trimmedNode);
document.querySelector(".length").textContent = length;
document.querySelector(".input").innerHTML = html;
document.querySelector(".raw-output").textContent = htmlToLength(html, length);
<h2>Raw HTML input</h2>
<div class="raw-input"></div>
<h2>Rendered Input</h2>
<div class="input"></div>
<h2>Rendered output to length <span class="length">?</span></h2>
<div class="trimmed"></div>
<h2>Raw HTML output</h2>
<div class="raw-output"></div>


0
一个选项是你可以使用lodash/truncate中的_truncate,像这样:
import _truncate from "lodash/truncate";
import ReactHtmlParser from "react-html-parser";

function ParsedText() {
  var text = "<b>Hello</b> how are you today?";


  return (
    <div> 
      {ReactHtmlParser(_truncate(text, { length: 5 }))}
    </div>
  )

0
我理解的是你有一个HTML文本,并且需要进行以下操作:
  1. 移除HTML标签
  2. 将步骤1后的字符串截断为5个字符。
在这种情况下,可以使用正则表达式来完成。
import React from "react";
import "./styles.css";

export default function App() {
  const message = "<b>Hello</b> how are you today?";
  const messageString = message.replace(/<(.|\n)*?>/g, '');

  const subText = messageString.substring(0, 5);

  return <div>{subText}</div>;
}

点击这里查看一个可用的示例。

查看此处此处的链接,了解如何在JS中从字符串中删除HTML标记的更多信息。

关于包html-react-parser,它不会返回字符串,因此substring方法将无法使用。它返回一个数组。在您的情况下,行parse(<b>Hello</b> how are you today?);将返回以下内容enter image description here


1
你好 - 感谢您的回复,我非常感激。我刚刚查看了您的代码沙盒,似乎粗体正在丢失。我想在结果中保留HTML标记,但不计算它们在截断中的字符数。因此,字符串长度为5的结果应该是<b>Hello</b>或Hello,就像页面上呈现的那样。 - Katie7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接