Skip to content
uencoder
TUTORIAL

How to Remove HTML Tags from Text

Strip HTML markup to get plain text, preserving content and handling entities.

Problem

You have HTML content and need the plain text without any tags or markup.

Prerequisites

  • Understanding of HTML structure
  • Knowledge of HTML entities

Steps

  1. 1. Parse the HTML

    Use an HTML parser rather than a regex to strip tags. A parser correctly handles nested tags, attributes with > characters, and self-closing tags. Regex-based stripping can fail on edge cases like <script> blocks or attribute values containing >.

    Input
    <p>Hello <b>world</b></p>
    Output
    parsed structure
  2. 2. Extract text content

    Walk the parsed DOM and collect text nodes. Skip script and style elements whose content is not visible text. Handle <br> as line breaks and <p> as paragraph breaks. The result is the visible text content.

    Input
    <p>Hello <b>world</b></p>
    Output
    Hello world
  3. 3. Decode HTML entities

    After stripping tags, decode HTML entities (&amp; → &, &lt; → <, &#39; → ', &nbsp; → space). This recovers the original characters that were escaped in the HTML. Use a standard entity decoder for the full named and numeric entity set.

    Input
    &amp; &lt; &#39;
    Output
    & < '

Expected result

Plain text with all HTML tags removed and entities decoded.

Common errors

Using regex to strip tags fails on edge cases
Use a proper HTML parser. Regex cannot correctly handle nested tags, attributes with >, or CDATA sections.
Script content appears in output
Explicitly skip <script> and <style> elements when extracting text. Their content is code, not visible text.

Troubleshooting

  • If entities appear as literal text, run an entity decoder after stripping.
  • If whitespace is wrong, normalize spaces and line breaks after extraction.

Security limits

  • Stripping HTML tags prevents XSS in display contexts, but always also sanitize any remaining text for safe output.

Related tools

Related tasks

Ready to run it?

References