Javascript Remove Html Tags From String

7 min read

JavaScript Remove HTML Tags From String: Complete Guide With Code Examples

Removing HTML tags from a string in JavaScript is one of those everyday tasks that looks trivial until you hit malformed markup, encoded entities, or a <script> payload hiding inside user-submitted text. Whether you are building a search result snippet, cleaning rich-text editor output, generating a meta description, or sanitizing user-generated content, knowing how to strip HTML tags safely and correctly will save you from broken layouts and serious security holes. This guide walks through every practical approach — regex, DOMParser, temporary elements, and server-side alternatives — and explains exactly when each one is the right choice.

Why You Need to Remove HTML Tags From a String

HTML markup is designed for browsers, not for plain-text contexts. The moment you try to use HTML-rich content somewhere that expects raw text, problems appear:

  • Text length calculations break. A string like <p>Hello <strong>world</strong></p> is 34 characters long, but the visible text is only 11. Character counters, SMS limits, and excerpt truncation all become wrong.
  • Layouts get corrupted. Injecting <div> markup into an attribute, a <textarea>, or a plain-text email template produces visibly broken output.
  • Security risks multiply. Rendering untrusted HTML through innerHTML opens the door to cross-site scripting (XSS).
  • SEO and analytics data becomes noisy. Meta descriptions, Open Graph tags, and structured data fields should contain clean text, not stray <span> fragments.
  • Non-HTML destinations reject it. CSV exports, JSON payloads, log files, and terminal output all need plain strings.

The core idea is simple: strip the tags, keep the human-readable content. The difficulty lies in doing that without accidentally deleting legitimate text or executing malicious code Took long enough..

Understanding What You Are Actually Removing

Before writing code, it helps to be precise about the target. An HTML tag is an opening or closing marker such as <p>, </p>, <img src="x.png" />, or <!And -- a comment -->. What you usually want to keep is the text node content between those markers.

There are three distinct layers to deal with:

  1. Tags — <h2>, </a>, <br />
  2. Attributes — the href="..." and class="..." parts inside a tag
  3. HTML entities — &amp;, &lt;, &nbsp;, &#8217;

Many tutorials stop after step one, which is why their output still shows &amp; where an ampersand should be. A complete solution handles all three Still holds up..

Method 1: Using Regular Expressions (Regex)

The most common approach is a simple regex replace. It is fast, dependency-free, and works in any JavaScript environment including Node.js.

function stripTags(html) {
  return html.replace(/<[^>]*>/g, '');
}

const input = '

Hello world!

'; console.log(stripTags(input)); // "Hello world! ### How the Pattern Works - `<` matches the opening bracket of a tag. - `[^>]*` matches any character that is **not** a closing bracket, zero or more times. - `>` matches the closing bracket. - The `g` flag replaces **all** matches, not just the first. ### A More Defensive Regex The naive pattern fails on comments, script blocks, and attributes containing a `>` character. A stronger version looks like this: ```javascript function stripTags(html) { return html .replace(/)<[^<]*)*<\/script>/gi, '') .replace(/)<[^<]*)*<\/style>/gi, '') .replace(//g, '') .replace(/<[^>]+>/g, '') .replace(/\s+/g, ' ') .trim(); }

The first two lines remove <script> and <style> blocks including their contents. This matters because a plain tag-stripping regex leaves the JavaScript source code behind as visible text — a common and embarrassing bug.

The Honest Limitation of Regex

HTML is not a regular language. Now, it is a nested, forgiving, error-tolerant format, and regex cannot reliably parse nested structures. Worth adding: browsers will happily render <p>one<p>two or <b><i>broken</b></i>. Regex has no concept of that nesting.

Use regex when:

  • The input is simple, controlled markup you generated yourself. Here's the thing — - You are running in a non-browser environment with no DOM. - Performance is critical and you are processing huge volumes of text.

Avoid regex when the input is arbitrary user content or security-sensitive.

Method 2: Using DOMParser (Recommended for Browsers)

DOMParser is a built-in browser API that parses a string into a real Document object, following the same HTML parsing rules as the browser itself. It is the most correct client-side approach.

function stripHtml(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || '';
}

const html = '

Title

Body & more

'; console.log(stripHtml(html)); // "TitleBody & more"

Why This Is Better

  • Correct parsing. Malformed markup is handled exactly the way a browser handles it.
  • Automatic entity decoding. &amp; becomes &, &nbsp; becomes a space, &#8217; becomes a curly apostrophe.
  • Inert by default. A document created by DOMParser is not attached to the page, so <img onerror="..."> and similar payloads do not fire. Scripts do not execute.

Adding Spacing Between Block Elements

textContent concatenates text nodes without separators, so <p>One</p><p>Two</p> becomes OneTwo. Fix it by inserting spaces before extracting text:

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

  doc.querySelectorAll('br').That said, forEach(br => br. replaceWith(' '));
  doc.Even so, querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, tr, section, article')
     . forEach(el => el.

  return (doc.body.textContent || '').replace(/\s+/g, ' ').trim();
}

console.log(htmlToText('

One

Two

')); // "One Two"

The Temporary Element Technique

A related classic approach creates a detached element and assigns the HTML to it:

function stripTags(html) {
  const

```javascript
function stripTags(html) {
  const el = document.createElement('div');
  el.innerHTML = html;
  return el.textContent || el.innerText || '';
}

This is shorter than the DOMParser version and works in every browser, but it carries a subtle risk. So naturally, assigning to innerHTML on a detached element does not execute <script> tags, yet browsers may still begin fetching resources referenced by the markup — and inline event handlers such as <img src=x onerror="alert(1)"> can fire even when the element is never attached to the document. If the HTML is untrusted, prefer the DOMParser approach, which is inert by design.

Method 3: Sanitizing Libraries

When you are handling arbitrary or user-supplied content, reach for a dedicated library rather than rolling your own. Two stand out:

  • sanitize-html — strips tags and whitelists what survives, so you can allow <b>, <a>, and <p> while dropping everything dangerous.
  • striptags — a tiny, focused package that does exactly one thing: remove all tags and decode entities.
import sanitizeHtml from 'sanitize-html';

const dirty = '

Hello

'; const clean = sanitizeHtml(dirty, { allowedTags: ['p', 'b', 'i'], allowedAttributes: {} }); console.log(clean); // "

Hello

"

The key advantage is that these libraries are maintained against the latest parsing quirks and XSS vectors. Security is a moving target, and a well-vetted dependency moves with it.

Choosing the Right Method

Scenario Recommended approach
Simple markup you control Regex
Browser, general-purpose extraction DOMParser
Browser, untrusted input sanitize-html
Node.js / server-side sanitize-html or a parser like node-html-parser
No DOM, no dependencies allowed Regex (with caution)

A quick rule of thumb: if a human didn't write the HTML, don't trust a regex with it.

Conclusion

Stripping HTML in JavaScript ranges from a one-line regex to a full sanitization pipeline, and the right choice depends entirely on where the markup comes from and what you intend to do with the result That's the whole idea..

For content you generated yourself, a regex is fast and perfectly adequate. On the flip side, for anything rendered in a browser, DOMParser gives you correct parsing and automatic entity decoding while staying inert and safe. And for untrusted input in production, a maintained library like sanitize-html is the only responsible option — it protects against the malformed markup and injection attacks that ad-hoc solutions inevitably miss.

The recurring lesson across all three methods is the same: HTML is more forgiving and more dangerous than it looks. Match your tool to your threat model, decode entities deliberately, and never assume that text which looks clean actually is.

Just Published

Brand New Reads

If You're Into This

You May Find These Useful

Thank you for reading about Javascript Remove Html Tags From String. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home