str.replace(/\x26/g,'\x26amp;')
.replace(/\x3c/g,'\x26lt;')
.replace(/\r\n|\n/g,'\x3cbr>');
- 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:
(
function(enc, e1, e2, e3){
(e1.onkeyup = function(){
e3.innerHTML = e2.value = enc(e1.value);
})();
}(
(function(){
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)
);};
}
)()
, document.getElementsByTagName('textarea')[0]
, document.getElementsByTagName('textarea')[1]
, document.getElementsByTagName('pre')[0]
)
);
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!