Regex for HTML Tags
This pattern finds individual tags — <p>, </div>, <img src="a.png" /> — so you can strip markup from short, trusted snippets by replacing every match with an empty string. It isn't anchored, so it finds tags anywhere in the text. Regex can't parse real HTML, though: comments, scripts and attribute values containing > will trip it up.
/<\/?[a-zA-Z][a-zA-Z0-9-]*\b[^>]*>/How it works, token by token
| Token | Meaning |
|---|---|
| < | the opening angle bracket |
| \/? | an optional slash, for closing tags |
| [a-zA-Z] | the tag name starts with a letter — so 'a < b' doesn't match |
| [a-zA-Z0-9-]* | the rest of the name, including hyphens for custom elements |
| \b | a word boundary: the name ends here |
| [^>]* | attributes: anything up to the next > |
| > | the closing bracket |
What it matches
<p></div><img src="a.png" alt="" /><my-element class="x">a < b3 <5plain textTry it live
One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.
Variations
<!--[\s\S]*?-->HTML comments, including multi-line ones<(script|style)\b[^>]*>[\s\S]*?<\/\1>a whole script or style element, contents includedLanguage notes
- To remove every tag in JavaScript, add the g flag to replace(); without it only the first tag goes. Python's re.sub replaces all matches by default.
Frequently asked questions
Is stripping tags with regex safe for user input?
No. It's fine for tidying trusted snippets, but it is not an HTML sanitizer — crafted input can slip markup through. Use DOMPurify, or DOMParser and textContent, for anything untrusted.
Why can't regex parse HTML?
HTML nests arbitrarily and has many special cases — comments, CDATA, attribute values containing >, unclosed tags. Regular expressions can't track nesting, so use a real parser for anything beyond simple matching.
Building something custom? The regex tester gives you live match highlighting for any pattern.