Skip to content

Instantly share code, notes, and snippets.

@KargJonas
Last active May 22, 2021 12:34
Show Gist options
  • Select an option

  • Save KargJonas/f33208a69d78445392d12f24ef0d4ecf to your computer and use it in GitHub Desktop.

Select an option

Save KargJonas/f33208a69d78445392d12f24ef0d4ecf to your computer and use it in GitHub Desktop.
RegEx' to select HTML tags.

RegEx' to select HTML-tags

Two great tools for testing RegEx:


Types of tags:

Start:

<h1 ... >

End:

</h1 ... >

Empty:

<h1 ... />  or  <h1 ... >

Select start tag

/<[a-zA-z]+\w*\s*(\s+(\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*){0,1}>/gim

Select end tag

/<\/[a-zA-z]+\w*\s*(\s+[^<]*){0,1}>/gim

Select empty tag and start tag

/<[a-zA-z]+\w*(\s*|(\s*\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*)\/{0,1}>/gim

Select any type of tag

/<([a-zA-z]+\w*(\s*|(\s*\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*)\/{0,1}|\/[a-zA-z]+\w*\s*(\s+[^<]*){0,1})>/gim

Select tags and content (if content does not contain < or >)

/<[a-zA-z]+\w*(\s*|(\s*\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*)>[^<>]*<\/[a-zA-z]+\w*\s*(\s+[^<]*){0,1}>/gim

Select tags and content

/<[a-zA-z]+\w*(\s*|(\s*\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*)>[\s\S]*<\/[a-zA-z]+\w*\s*(\s+[^<]*){0,1}>/gim

Select empty- and non-empty tags with content (if content does not contain < or >)

/<[a-zA-z]+\w*(\s*|(\s*\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*)(>[^<>]*<\/[a-zA-z]+\w*\s*(\s+[^<]*){0,1}|\/{0,1})>/gim

Select empty- and non-empty tags with content

/<[a-zA-z]+\w*(\s*|(\s*\w+(\s*=\s*("[^"]*"|'[^']*')){0,1}\s*)*)(>[\s\S]*<\/[a-zA-z]+\w*\s*(\s+[^<]*){0,1}|\/{0,1})>/gim

Some cases those will work in:

<div class="my-test-div">
	<script src="path/to/my/script" defer></script>
	<h1 style = "color: red" >Hello World</h1>
	<img src= "path/to/my/img.png">
	<div my-own-attr="<haha>" />
</div>

Please tell me if you see a mistake.
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment