Regex to Match Self-Closing HTML/XML Tags
Match self-closing HTML and XML tags like <br/>, <img/>, and <input/> with this regex. Captures the tag name in a group. Free regex tester.
Regular Expression
/<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*\/>/g
Token Breakdown
| Token | Description |
|---|---|
| < | Matches the literal character '<' |
| ( | Start of capturing group |
| [a-zA-Z] | Character class — matches any one of: a-zA-Z |
| [a-zA-Z0-9] | Character class — matches any one of: a-zA-Z0-9 |
| * | Matches the preceding element zero or more times (greedy) |
| ) | End of group |
| \b | Word boundary assertion |
| [^>] | Negated character class — matches any character NOT in > |
| * | Matches the preceding element zero or more times (greedy) |
| \/ | Matches a literal forward slash |
| > | Matches the literal character '>' |
Detailed Explanation
This regex matches self-closing tags used in HTML and XML. Here is the token-by-token breakdown:
< — Matches the literal opening angle bracket that starts every HTML or XML tag.
([a-zA-Z][a-zA-Z0-9]*) — Capturing group 1 matches the tag name. It must start with a letter followed by zero or more letters or digits. This captures names like br, img, input, and custom elements.
\b — A word boundary assertion ensuring the tag name ends at a word boundary. This prevents partial matches on tag names and separates the name from any following attributes.
[^>]* — Matches zero or more characters that are not a closing angle bracket. This consumes any attributes within the tag such as class, id, src, or other attribute-value pairs.
/> — Matches the self-closing delimiter: a forward slash followed by a closing angle bracket. The forward slash is escaped with a backslash for clarity, though it is not strictly necessary in JavaScript regex. This is the defining characteristic of a self-closing tag.
The g flag enables global matching to find all self-closing tags in the document. This pattern is particularly useful in XML processing where self-closing tags are common, React JSX analysis, and XHTML validation. In HTML5, void elements like br, hr, and img do not require the closing slash, but this pattern specifically targets the self-closing syntax.
Example Test Strings
| Input | Expected |
|---|---|
| <br/> | Match |
| <img src="photo.jpg" /> | Match |
| <div>content</div> | No Match |
| <input type="text"/> | Match |
| <p>paragraph</p> | No Match |
Try It — Interactive Tester
Match Highlighting(3 matches)
Matches & Capture Groups
33 charsFlags: gMatches: 3Ctrl+Shift+C to copy regex