Search This Blog

Loading...

Sunday, September 9, 2012

IntelliJ: HTML and structural search and replace

I was asked to do some quick fix on some website. The website used a lot of table structures for laying out the page. To give an impression, the page had more than 50 tables each with 4 columns and 20+ rows.

There was no external CSS used. All styling of the tables was done with attributes or inline style elements. The styling was also not consistent throughout the page so each table looked slightly different.

Here is an example:

<table>
    <tr>
        <td width="200px">Some text</td>
        <td width="221px">More text</td>
        <td width="300px" height="100px">Example</td>
        <td style="width: 210px;">HelloWorld</td>
        <td style="width: 190px;">More text</td>
        <td id="test" style="width: 222px;"></td>
        <td id="test2" class="right" style="width: 200px;">Java</td>
    </tr>
</table>

Without rewriting the whole site at once I wanted to remove all the inline styles so I could use css to style all the tables the same. That at least looked more attractive in the short run while in the long run we could focus on a complete redesign of the site.

The first thing I wanted to do was replace all the td elements with inline styling with plain, empty td elements. As written in my previous posts, IntelliJ's structural search and replace features fits this use case nicely.

In the structural search and replace dialog I used the following:

Search template:

<td $width$="$value$" $style$="$value$">$text$</td>

Replace template:
<td>$text$</td>

In the Edit variables dialog I specified a minimum count of zero for the $width$, $style$ and $text$ variable. The $value$ variable has a minimum count of one. For all variables I used a maximum count of one.

The template searches for all td elements with zero or one width or style attributes (or both) and with or without text. The replace template replaces the td found with the search template in a plain td. The output of the HTML after the search and replace is run is:

<table>
    <tr>
        <td>Some text</td>
        <td>More text</td>
        <td>Example</td>
        <td>HelloWorld</td>
        <td>More text</td>
        <td></td>
        <td>Java</td>
    </tr>
</table>

After this replacement I could just insert the appropriate CSS and style all tables consistently. Without structural search and replace I think such scenario's take considerably longer to execute.

Hope you enjoyed it.

If you have other interesting structural search and replace use cases please share them.