Render tab characters in HTML
replace \t
with
.
Each space you want will be a
As pointed out this isn't completely correct as it only pretends to be a tab as HTML doesn't actually output format a tab as you would expect.
An alternative to the non-breaking space would be the em space ( 
or  
). It is usually rendered as a longer space, if that is an advantage.
A Quick & Dirty Way
For a quick fix, you can use the xmp
tag to stop the browser from collapsing whitespace. The xmp
tag contains text that should be rendered uninterpreted (and in a monospaced font).
The problem is that xmp
tags have been deprecated since HTML3.2, and have been dropped from the HTML5 spec altogether. In practice, browsers still support xmp
tags, so they can still be useful, but not in production.
The Proper Way
Tabs are for tabulating data. The proper way to tabulate data in HTML is to use the table
tag. Every line in your original string translates to a row in the table, while each tab in the original string starts a new (left-aligned) cell in the table.
Imagine you had this (tab-aligned) string to begin with:
Spam 1.99
Cheese 2.99
Translated to HTML, that string would look like this:
<table>
<tr> <td> Spam </td> <td> 1.99 </td> </tr>
<tr> <td> Cheese </td> <td> 2.99 </td> </tr>
</table>
Note: If you wrapped the tab-aligned string in xmp
tags and styled the HTML table to look like plain text, the rendered results would be the same.
Why not just wrap the content in a <pre>
tag? This will handle the \n
as well as the \t
characters.