Convert HTML to Plain Text in React

How HTML-to-plain-text conversion works in React, what it removes, how to do it safely, and when plain text is the better choice than sanitized HTML.

Converting HTML to plain text in a React app turns a string of markup into a string of characters. Tags are removed and entities are decoded. Teams usually need this for previews, notifications, metadata, in-app search and character counts. This review explains what the conversion changes, what it costs, how to do it without opening a security hole, and when you should render sanitized HTML instead.

Is plain text the right output for your use?

Plain text is a good fit when the destination needs only characters. It is a poor fit when the structure of the content carries meaning. The main benefit is predictability: a plain string rendered through JSX is escaped by React, behaves the same everywhere it is pasted, and can be measured, searched and truncated. The deciding tradeoff is loss of structure. Anything the markup expressed through tags, such as link targets, list numbering, table layout, emphasis and image alt text, disappears unless your conversion writes it out as characters.

  • Plain text is usually preferable for:
  • Card previews, excerpts and snippets
  • Page titles, meta descriptions and document titles
  • Push notifications, SMS bodies and other text-only channels
  • aria-label values, tooltips and title attributes
  • Indexing content for in-app search or filtering
  • Character or word counts and length limits
  • The text/plain fallback when copying rich content to the clipboard
  • Keep sanitized HTML instead when:
  • Readers need working links, not just link text
  • Headings, lists or tables organize the content
  • Assistive technology users depend on semantic structure to navigate
  • The output will be edited and saved back as rich content

What the conversion actually changes

Converting HTML to text changes the stored string. It is not a visual effect. CSS that hides elements or restyles text, and bidirectional display controls, leave the underlying characters alone. Conversion instead produces a new string with different content. Terms that come up in other text-transformation tools, such as reversing, mirroring or decorative fonts, do not apply here. Character order is preserved and no lookalike Unicode characters are substituted. Only the markup is removed, along with whatever the markup encoded.

  • Tags are removed and only text nodes remain.
  • Entities are decoded: & becomes &, < becomes <, and   becomes U+00A0, a non-breaking space that differs from an ordinary space.
  • Source whitespace, including indentation and line breaks in the HTML file, is carried through as-is by textContent. The line breaks a browser would show between block elements are not added.
  • Link URLs are dropped. Only the anchor text survives.
  • Image alt text is dropped, because it lives in an attribute and not in a text node.
  • List bullets and ordered-list numbers disappear, because the browser generates them during rendering and they are not part of the text.
  • Table cells run together with no separators.
  • The contents of script and style elements inside the body are included by textContent unless you remove those elements first.

textContent versus innerText

textContent returns every text node in source order, ignores CSS, and adds no line breaks for block elements. innerText is layout-aware. On an element the browser is actually rendering, it skips content hidden with display: none, inserts line breaks between block-level elements, and applies CSS text-transform. On an element that is not being rendered, which includes anything inside a document created by DOMParser, innerText falls back to textContent. To get innerText's layout-aware behavior, the content has to be mounted and visible in the live page.

Approaches in a React project

Approach | Runs where | Keeps line breaks | Notes
DOMParser + textContent | Browser only | No, unless you add them | Parses into an inert document. Simple and safe for untrusted input.
innerText on a rendered element | Browser only, element must be visible | Yes, based on layout | Depends on CSS. The content must already be on the page.
Regex tag stripping | Anywhere | No | Misses comments, attributes containing >, and entity decoding. Not a safe sanitizer.
Dedicated library such as html-to-text | Node and bundlers | Yes, by design | Built to format elements like links, lists and tables as text. Check its current documentation for options and defaults.

A browser-side helper

const BLOCK_SELECTOR = 'p, div, li, tr, h1, h2, h3, h4, h5, h6, blockquote, pre';

export function htmlToText(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  const { body } = doc;

  body.querySelectorAll('script, style, noscript, template').forEach((el) => el.remove());

  // Collapse source whitespace (not U+00A0) outside <pre>.
  const walker = doc.createTreeWalker(body, NodeFilter.SHOW_TEXT);
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
    if (!node.parentElement?.closest('pre')) {
      node.data = node.data.replace(/[ \t\r\n\f]+/g, ' ');
    }
  }

  body.querySelectorAll('br').forEach((br) => br.replaceWith('\n'));
  body.querySelectorAll(BLOCK_SELECTOR).forEach((el) => el.append('\n'));

  return body.textContent
    .replace(/ *\n */g, '\n')
    .replace(/\n{3,}/g, '\n\n')
    .trim();
}

Treat this helper as a starting point. It removes non-content elements and collapses whitespace from the HTML source. It turns br into a newline and ends each block element with one. Non-breaking spaces are kept, because the regex lists only HTML whitespace characters rather than using \s, which in JavaScript also matches U+00A0. One limitation: the final cleanup trims spaces around every line break, which also flattens leading-space indentation inside pre blocks. Handle code blocks separately if their indentation matters. Link URLs, alt text and list numbering are still lost. If you need them, write them into the DOM as text before reading textContent.

Using it in a component

import { useMemo } from 'react';
import { htmlToText } from './htmlToText';

function truncateGraphemes(text, max) {
  const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
  const segments = [...segmenter.segment(text)];
  if (segments.length <= max) return text;
  return segments.slice(0, max).map((s) => s.segment).join('').trimEnd() + '…';
}

export function Preview({ html, maxLength = 160 }) {
  const text = useMemo(() => htmlToText(html), [html]);
  return <p style={{ whiteSpace: 'pre-line' }}>{truncateGraphemes(text, maxLength)}</p>;
}

Rendering the result as a JSX child means React escapes it, so decoded characters such as < appear as text and are never parsed as markup. The white-space: pre-line style is a presentation choice. It makes the stored newlines visible without changing the string. Truncation uses Intl.Segmenter because slicing by string length counts UTF-16 code units. A plain slice can split an emoji built from several code points, such as a family or flag sequence, or separate a letter from its combining accent.

Server-side rendering

DOMParser and NodeFilter are browser APIs and do not exist in Node. If the component renders on the server, as with frameworks that use server components or server-side rendering, the helper will throw there. You have three options: run the conversion with a library that works in Node, convert ahead of time where the content is stored, or move the conversion into client-only code. Moving it to the client means the server-rendered HTML will not contain the preview text, so check that this mismatch is acceptable for your page.

Safety pitfalls

Do not extract text by assigning untrusted HTML to the innerHTML of an element in the live document, even a detached one created with createElement. Event-handler attributes such as an image's onerror can run. A document created by DOMParser is inert: scripts in it do not execute. Regex stripping is not a sanitizer and should never be the only barrier against injected markup. Watch for one trap in particular. Conversion decodes entities, so text that originally read <script> becomes a literal <script>. If that output is later passed to dangerouslySetInnerHTML, or concatenated into an HTML string, it becomes live markup. Keep the converted text on the text side of your app.

Readability after copying or sharing

Plain text pastes predictably. Destinations receive exactly the characters you produced, with no stray styling. The cost is that the destination cannot rebuild anything you discarded. A pasted link without its URL, or a table flattened into a run-on line, may be unusable. If users copy rich content out of your app, the clipboard can carry both formats. The destination then chooses: rich editors typically take the HTML, and plain fields take the text.

async function copyRichAndPlain(html, text) {
  const item = new ClipboardItem({
    'text/html': new Blob([html], { type: 'text/html' }),
    'text/plain': new Blob([text], { type: 'text/plain' }),
  });
  await navigator.clipboard.write([item]);
}

The asynchronous Clipboard API requires a secure context and generally a user gesture, and support for writing multiple formats differs between browsers. Feature-detect ClipboardItem and fall back to navigator.clipboard.writeText with the plain version when it is unavailable.

Accessibility depends on where the text ends up. For aria-label values and similar attributes, plain text is required, because those attributes cannot contain markup. For content shown on the page, replacing HTML with plain text removes the heading, list and link semantics that screen-reader users rely on to navigate. In that case, render sanitized HTML and use plain text only for derived pieces such as previews. Plain text is reading-order safe, because conversion keeps characters in source order. If CSS visually reorders the original content, though, the text follows source order, not visual order.

For search and editing, plain text is the right form to index and to match queries against. The conversion cannot be reversed: you cannot rebuild the original HTML from its text. Keep the HTML as the source of truth and derive plain text from it whenever you need it, rather than saving the text back over the original.

Limits of this review

No measurements, benchmarks or destination tests were supplied for this review. The behavior described here comes from documented browser and React APIs, not from testing in particular email clients, chat apps, content management systems or screen readers. Before relying on the output in a specific destination, test it there with your own content, including links, lists, tables, non-breaking spaces and emoji. Library options and defaults change between versions, so confirm them in the library's current documentation.