Andrew Tomazos
Andrew Tomazos

Reputation: 68738

Displaying raw text in HTML like a text editor

I have a UTF8 text string that I would like displayed in a div (or the entire <body>) in a web page according to the following rules:

Clearly I need to perform some preprocessing steps on the text string before I insert it into the web page (perhaps I need to replace certain characters with named entities &foo;. Perhaps I need to surround the text file with a certain tag, <pre> for example, etc).

Precisely what preprocessing steps do I need to perform to achieve the above. If there are multiple sets of steps that achieve the above, than please answer with the shortest/simplest.

Upvotes: 3

Views: 9881

Answers (2)

Thomas Shields
Thomas Shields

Reputation: 8943

A super-simple way of doing this without any preprocessing is to wrap it in a <textarea>.

HTML:

<textarea readonly class="code">
 <!DOCTYPE html>
   <html>
     <head>
       <meta charset=utf-8 />
       <title>My Code</title>
     </head>
     <body>
       My Content
     </body>
   </html>
</textarea>

CSS:

 .code {
    border:1px solid;
    width:500px;
    height:200px;
    overflow:auto;
    outline:none;
    resize:none;
  }

However, this is somewhat un-semantic as the textarea is for editing. If you don't care, though, it's a good solution - otherwise, I recommend Boldewyn's answer

http://jsbin.com/oxifek/edit#html,live

Upvotes: 2

Boldewyn
Boldewyn

Reputation: 82814

(1) and (3) are actually quite simple, if you serve your document as UTF-8 and you're fine with supporting IE >= 8. Then it's:

<body style="white-space: pre-wrap">
  (Your String here, '<' and '&' encoded to '&lt;' and '&amp;' respectively)
</body>

The white-space CSS property is the key here.

For (2) you will either need a pre-processing step (a la s/\t/ /g) or wait until all browsers support tab-size.

Upvotes: 4

Related Questions