Textarea \n to <br> without escaping
I am entering stuff in a textarea, and after I press a button, my JS takes the textarea input and puts it inside a div tag.
The problem is, when I enter a newline in the textarea, like so:
Hi
Goodbye
It comes out in the div as
Hi<br><br>Goodbye
When I use Firebug to inspect the actual HTML markup live, I see this in the div:
Hi<br> <br> Goodbye
This is a function I found that should replace the newlines开发者_运维知识库 with breaktags:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '\<br \/>' : '\<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
Here is how I use it:
etext = $('#mytext').val();
etext = nl2br(etext,false);
$('#mydiv').text(etext);
However as you see, it is not working.
How can I do this? If you need more code, do let me know
Perhaps it will work if you do:
$('#mydiv').html(etext);
...or with no framework:
document.getElementById("mydiv").innerHTML = etext;
The problem is that text() is automatically escaping your markup characters:
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as < for <).
精彩评论