Ensuring whitespace is visible

Monday 8th September

If you’ve ever dealt with logging or debugging your software, you’ve probably had to deal with the issue of whitespace. But how best to display this in HTML?

The problem

While testing some code recently, it became obvious that I needed a way of clearly identifying spaces in the output, particularly at the beginning and end of each item of text. This is something common enough in the world of console output, where enclosing output in some way (e.g. “[output ]”) is a simple solution. However, two factors made this slightly different when it came to displaying on the web:

The initial rendering was a table at its most basic:

inout
hello,worldhello, world
hello , worldhello, world
hello, world hello, world

In such a trivial example, you could guess that those entries in the ‘out’ column were all identical, with no leading/trailing space, but it’s difficult to be certain, especially when the output gets more complex.

The white-space property

First up, is the white-space property which defines, believe it or not, how whitespace is handled. The pre value, in effect, reproduces the behaviour of the <pre> element, and goes a long way to solving the problem:

inout
hello,worldhello, world
hello , worldhello, world
hello, world hello, world

Note that spacing is now quite a bit more obvious, especially around the comma on row 2, and at the beginning of row 3. It’s still a bit unclear, though, and I still found myself peering intensely at that table to try to ‘guess the spaces’.

Enter jQuery

So, jQuery to the rescue, and with a liberal sprinkling of <span> elements inserted around spaces, styled with a border and a pixel of margin, everything becomes a lot clearer:

inout
hello,worldhello, world
hello , worldhello, world
hello, world hello, world

Here’s the code, which runs on $('document').ready(); tables that require this treatment are marked up with a ‘mono’ class:

$('table.mono td').each(function() {
    var str = $(this).html();
    var newstr = '';

    for (i = 0; i < str.length; i++)
        newstr += str[i] == ' ' ? '<span>' + str[i] + '</span>' : str[i];

    $(this).html(newstr);
});

Comments

Leave a comment