DEV Community

Ivan Ševčík
Ivan Ševčík

Posted on

Refactoring HTML code with help of regex search and replace

Recently I had to do a lot of refactoring in HTML templates. Current IDEs usually don't provide many tools for refactoring HTML code so we had to help ourselves. Let's see if we could leverage old good search & replace and a bit of regular expressions.

The goal was to remove old component record-item from templates and replace it with new markup composed just of divs and spans. This one simple change just repeated so many times it would be tedious to do it all manually:

<!-- old code -->
<record-item label="Name">
    {{ details.name }}
</record-item>
<record-item *ngIf="details.color" label="Color">
    {{ details.color }}
</record-item>

<!-- new code -->
<div class="record">
  <span class="label">Name</span>
  <span class="value">{{ details.name }}</span>
</div>
<div *ngIf="details.color" class="record">
  <span class="label">Color</span>
  <span class="value">{{ details.color }}</span>
</div>
Enter fullscreen mode Exit fullscreen mode

The complication was that record-item component had one input as attribute that needed to be converted as content of span element in the new code. On top of that a condition like *ngIf="details.color" could be set on the old component which would also need to be present on div element in the new code.

I originally thought that the optional condition is a complication that would require two distinct search regulars - one for occurrence with the condition and the other for occurrence without the condition. It turned out later that it would not. Let's check the regular.

Regular expression for search and replace:

//search regex
const search = /(<hfc-review-section-item) (\*ngIf="[^"]+")? ?label="(.*)".*>(.*)<\/hfc-review-section-item>/

//replace with
const replace = "<div $2 class="record">\n<span class="label">$3</span>\n<span class="value">$4</span>\n</div>"
Enter fullscreen mode Exit fullscreen mode

Every piece of code that needs to be transferred into new one is captured in its own group.

Group for possible condition *ngIf="..." has optional modifier ?

Then a final result is composed from new HTML markup and captured groups.

Finally, I was able to successfully replace all my templates with this simple regex and have saved a lot of time and avoided possible typos by not doing it manually.

Oldest comments (0)