breakitdown

Regex to match or strip HTML tags

Answer

s.replace(/<[^>]*>/g, "") removes anything from a < to the next >. That is fine for stripping simple tags from text you control. It is not a parser and not a sanitizer: for untrusted HTML, use DOMParser and read textContent, or a library like DOMPurify.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. <The character '<' literallyliteral
  2. [^>]Any one character except '>'character class
  3. *Repeat the class zero or more times, as many as possible (greedy)quantifier
  4. >The character '>' literallyliteral

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
<p>Hello</p>✓ match
<br/>✓ match
<a href="/x">link</a>✓ match
plain text✗ no match
a < b✗ no match
if a < b and c > d✓ match
<!-- comment -->✓ match
<✗ no match

Try your own text

One string per line: each line is tested on its own (the m flag is added here).

How it works

[^>]* means "anything except >", so each match stops at the first closing bracket. That is what keeps <b>bold</b> from being matched as one long tag, which is what greedy <.*> would do (see greedy vs lazy).

HTML is not a regular language. Tags nest, attribute values can contain >, comments can contain tags, and <script> content has its own rules. A regex sees characters, not structure, so each of those cases produces a wrong result. The examples show some of them.

Variants

Gotchas

Related explainers

← Explain any regular expression