Template for displaying text on a web page created from <textarea>

Problem

What is a simple and effective template for displaying text on a web page that originated from an element <textarea>

while retaining the original formatting?

purpose

The goal is to allow the client to type whatever they want into <textarea>

, and so that they can view it later using all the characters and line breaks they used.

Anything using Javascript, JQuery or Backbone would be great.

More details

Three (wrong) methods I've tried so far:

  • Displaying text with jQuery('element').html()

    • The problem with this method is that the html-matching characters that the client may have chosen to enter into the textbox are interpreted as html like >

      and<

  • Displaying text with jQuery('element').text()

    • The problem with this method is that any line breaks that the client has chosen to use are discarded.
  • Displays text in a <textarea>

    read-only item .
    • The problem with this method is that it is difficult to get it to <textarea>

      expand to the exact size of the text. It also leaves a lot to be desired in terms of attractive formatting.
+3


source to share


1 answer


str.replace(/\x26/g,'\x26amp;')     // first do all & to &amp;
   .replace(/\x3c/g,'\x26lt;')      // next do < to &lt;
   .replace(/\r\n|\n/g,'\x3cbr>');  // finally replace new lines with <br>
// Note: I chose hex char code to exclude the 'risky' characters from the code,
//  that way they are also safe for inline-scripts (in older browsers).
// Also, I used local setting char-notation, not unicode, 
//  as they are the same for this purpose (and it saves some chars).

      

  • Note: The order of replacement is important.
  • Also note that this sequence did not end up trying to preserve whitespace (otherwise avoid collapsing whitespace in HTML) if you find the HTML equivalent of & nbsp; ... which is break; '(and replace whitespace with that) because it's much easier to use a tag pre

    to store content (better for older browsers, especially IE <9), or turn off the collapse white space feature in CSS:div.preview {white-space: [pre|pre-wrap];}

Simple example ( live jsFiddle here ):

<textarea style="width:98%" onkeyup="
this.nextSibling.innerHTML=this.value.replace(/\x26/g,'\x26amp;')
                                     .replace(/\x3c/g,'\x26lt;')
                                     .replace(/\r\n|\n/g,'\x3cbr>');
"></textarea><pre></pre>

      

Note that you can also connect onchange

, etc. Also, you may want to have a separate function and cache the output (and input) items.

You can make it much more difficult, for example, only replace &

when absolutely necessary, same for <

.
Alternatively, you can convert all unwanted (non-ASCII) characters to their unicode HTML entity equivalent, but this all seems a bit overkill for a simple preview, as you probably want, don't want to send user data to that (over the top effective) html markup. A simple example for this would be the following:



.replace(/[^\u0020-\u007e]/g, function(m){return '\x26#'+m.charCodeAt(0)+';';})

      

Hope this helps you.


EDIT 1: Also see jsFiddle v2 demo and jsFiddle v3 demo for some more complex examples like:

(  // START HTML encoder hookup 
 function(enc, e1, e2, e3){
   (e1.onkeyup = function(){
      e3.innerHTML = e2.value = enc(e1.value);
   })();
 }( // IIFE Passing encoder and elements
   (function(){  //HTML enc
      var  amp=/\x26/g  ,  lte=/\x3c/g  ,  eol=/\r\n|\n/g
      , noASCI=/[^\u0020-\u007e]/g
      , toUCPd=function(m){ return '\x26#'+ m.charCodeAt(0) +';'; }
      ;
      return function(s){return( 
        s.replace(amp, '\x26amp;')
         .replace(lte, '\x26lt;')
         .replace(eol, '\x3cbr>')
         .replace(noASCI, toUCPd)      //optional
      );};
    }
   )() //IIFE returns HTML enc
 , document.getElementsByTagName('textarea')[0]
 , document.getElementsByTagName('textarea')[1]
 , document.getElementsByTagName('pre')[0]
 )
); // END HTML encoder hookup

/* Corresponding demo html:
Input:<br>
<textarea>&#9;&lt;this is a tab char  &  these &#9786;&#235; non-'ASCII'
continue to to type here</textarea><br>
Generated HTML code:<br>
<textarea>code output</textarea><br>
HTML output in pre:<br>
<pre>html output</pre>
*/

      


EDIT 2: almost forgot, you could have a look at the (dodgy, forgotten, but still valid) xmp

-tag
. This will work until the user types </xmp

. Note for older IE: replace the entire xmp element instead of installing / overwriting it innerHTML

(because that doesn't work, at least in IE6). However, as noted, there are a lot of quirks for this xmp

-tag regarding box layout, overflow, etc. In different browsers!

+1


source







All Articles