jQuery text() and newlines

JavascriptJqueryHtml

Javascript Problem Overview


I want to be able to say

$(someElem).text('this\n has\n newlines);

and it renders with newlines in the browser. The only workaround I have found is to set the css property 'white-space' to 'pre' on someElem. This almost works, but then I have an annoyingly large padding between the text and the top of someElem, even when I set padding to 0. Is there a way to get rid of this?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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>

Solution 3 - Javascript

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"));

Solution 4 - Javascript

Alternatively, try using .html and then wrap with <pre> tags:

$(someElem).html('this\n has\n newlines').wrap('<pre />');

Solution 5 - Javascript

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, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

Solution 6 - Javascript

Try this:

$(someElem).html('this<br> has<br> newlines);

Solution 7 - Javascript

I would suggest to work with the someElem element directly, as replacements with .html() would replace other HTML tags within the string as well.

Here is my function:

function nl2br(el) {
  var lines = $(el).text().split(/\n/);
  $(el).empty();
  for (var i = 0 ; i < lines.length ; i++) {
    if (i > 0) $(el).append('<br>');
    $(el).append(document.createTextNode(lines[i]));
  }
  return el;
}

Call it by:

someElem = nl2br(someElem);

Solution 8 - Javascript

Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.

Solution 9 - Javascript

For me it works when using jquerys .html() function instead of .text() function. Then you can add <br/> for linebreaks.

var msg = someString + "<br/>" + anotherString;
$(elem).html(msg);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe ArmstrongView Question on Stackoverflow
Solution 1 - JavascriptcleongView Answer on Stackoverflow
Solution 2 - JavascriptJosé Roberto Araújo JúniorView Answer on Stackoverflow
Solution 3 - JavascriptPeter V. MørchView Answer on Stackoverflow
Solution 4 - Javascriptkarim79View Answer on Stackoverflow
Solution 5 - JavascriptMark ByersView Answer on Stackoverflow
Solution 6 - JavascriptdaCodaView Answer on Stackoverflow
Solution 7 - JavascriptJochenJungView Answer on Stackoverflow
Solution 8 - JavascriptAndrew B.View Answer on Stackoverflow
Solution 9 - JavascriptRuwenView Answer on Stackoverflow