It's the year 2015. The correct answer to this question at this point is to use CSS white-space: pre-line
or white-space: pre-wrap
. Clean and elegant. The lowest version of IE that supports the pair is 8.
https://css-tricks.com/almanac/properties/w/whitespace/
P.S. Until CSS3 become common you'd probably need to manually trim off initial and/or trailing white-spaces.
If you store the jQuery object in a variable you can do this:
var obj = $("#example").text('this\n has\n newlines');
obj.html(obj.html().replace(/\n/g,'<br/>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
If you prefer, you can also create a function to do this with a simple call, just like jQuery.text() does:
$.fn.multiline = function(text){
this.text(text);
this.html(this.html().replace(/\n/g,'<br/>'));
return this;
}
// Now you can do this:
$("#example").multiline('this\n has\n newlines');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
Here is what I use:
function htmlForTextWithEmbeddedNewlines(text) {
var htmls = [];
var lines = text.split(/\n/);
// The temporary <div/> is to perform HTML entity encoding reliably.
//
// document.createElement() is *much* faster than jQuery('<div></div>')
// http://stackoverflow.com/questions/268490/
//
// You don't need jQuery but then you need to struggle with browser
// differences in innerText/textContent yourself
var tmpDiv = jQuery(document.createElement('div'));
for (var i = 0 ; i < lines.length ; i++) {
htmls.push(tmpDiv.text(lines[i]).html());
}
return htmls.join("<br>");
}
jQuery('#div').html(htmlForTextWithEmbeddedNewlines("hello\nworld"));
Alternatively, try using .html
and then wrap with <pre>
tags:
$(someElem).html('this\n has\n newlines').wrap('<pre />');
You can use html
instead of text
and replace each occurrence of \n
with <br>
. You will have to correctly escape your text though.
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
Try this:
$(someElem).html('this<br> has<br> newlines);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With