# Regex for HTML Tags

> HTML tag regex that matches opening, closing and self-closing tags, for stripping markup from simple snippets. Explained token by token, with its limits.

```
/<\/?[a-zA-Z][a-zA-Z0-9-]*\b[^>]*>/
```

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.

## 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 |

## Examples

- ✓ matches: `<p>`
- ✓ matches: `</div>`
- ✓ matches: `<img src="a.png" alt="" />`
- ✓ matches: `<my-element class="x">`
- ✗ does not match: `a < b`
- ✗ does not match: `3 <5`
- ✗ does not match: `plain text`

## Variations

- `<!--[\s\S]*?-->` — HTML comments, including multi-line ones
- `<(script|style)\b[^>]*>[\s\S]*?<\/\1>` — a whole script or style element, contents included

## Language 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.

## FAQ

### 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.

## Related patterns

- [Regex for URL Validation](https://www.devkult.com/regex/url.md)
- [Regex to Trim Leading and Trailing Whitespace](https://www.devkult.com/regex/trim-whitespace.md)
- [Regex for URL Slug Validation](https://www.devkult.com/regex/slug.md)

Open the interactive page: https://www.devkult.com/regex/html-tag