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?
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:
| in | out |
|---|---|
| hello,world | hello, world |
| hello , world | hello, 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.
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:
| in | out |
|---|---|
| hello,world | hello, world |
| hello , world | hello, 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’.
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:
| in | out |
|---|---|
| hello,world | hello, world |
| hello , world | hello, 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);
});