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
innerHTMLopens 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:
- Tags —
<h2>,</a>,<br /> - Attributes — the
href="..."andclass="..."parts inside a tag - HTML entities —
&,<, ,’
Many tutorials stop after step one, which is why their output still shows & 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(/';
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.