[javascript] jQuery text() and newlines

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?

This question is related to javascript jquery html

The answer is


If you store the jQuery object in a variable you can do this:

_x000D_
_x000D_
var obj = $("#example").text('this\n has\n newlines');_x000D_
obj.html(obj.html().replace(/\n/g,'<br/>'));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p id="example"></p>
_x000D_
_x000D_
_x000D_

If you prefer, you can also create a function to do this with a simple call, just like jQuery.text() does:

_x000D_
_x000D_
$.fn.multiline = function(text){_x000D_
    this.text(text);_x000D_
    this.html(this.html().replace(/\n/g,'<br/>'));_x000D_
    return this;_x000D_
}_x000D_
_x000D_
// Now you can do this:_x000D_
$("#example").multiline('this\n has\n newlines');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p id="example"></p>
_x000D_
_x000D_
_x000D_


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.


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.


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

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

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

Try this:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment