How do I remove HTML elements with different values in VS Code using Find & Replace, while keeping its contents?

Viewed 28

I'd like to remove all <a></a> elements (including classes, etc) in VS Code but keep the different values inside of the element. Is this possible using regular expression or another way?

This:

<td><a class="x">1</a></td>
<td><a class="y">2</a></td>
<td><a class="z">3</a></td>

Becomes:

<td>1</td>
<td>2</td>
<td>3</td>
2 Answers

I can help! Try the following in your find and replace tool for the find portion:

<a[^>]*>(.[^<]*)</a>

Then use the capture group for the replace portion:

$1

What this does is looks for <a then any number of characters that are not the closing angle bracket (>). Next it matches all characters up until the next opening angle bracket (<), then looks for the closing </a>. Finally, all the characters in the middle are what is used to replace the matched text, thanks to the capturing group $1.

You can do it with Emmet:

  • Select one </a>
  • Select All: Ctrl+Shift+L
  • Arrow Left (now you are just in front of all </a>)
  • Execute command: Emmet: Remove Tag
  • Esc to leave Multi Cursor

If there can be other tags inside the <a></a>

  • Select one </a>
  • Select All: Ctrl+Shift+L
  • Arrow Left (now you are just in front of all </a>)
  • Execute command: Emmet: Balance (outward)
  • Cut: Ctrl+X
  • Execute command: Emmet: Balance (outward) (select all <a....></a>)
  • Paste: Ctrl+V
  • Esc to leave Multi Cursor

If you only want to do this on particular <a....></a> tags don't use Select All: Ctrl+Shift+L but Ctrl+D and Ctrl+K Ctrl+D

If you need to do it a lot set some key bindings to the Emmet commands used

Related