[javascript] jQuery convert line breaks to br (nl2br equivalent)

I'm having jQuery take some textarea content and insert it into an li.

I want it to visually retain the line breaks.

There must be a really simple way to do this...

This question is related to javascript jquery line-breaks

The answer is


Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.


In the spirit of changing the rendering instead of changing the content, the following CSS makes each newline behave like a <br>:

white-space: pre;
white-space: pre-line;

Why two rules: pre-line only affects newlines (thanks for the clue, @KevinPauli). IE6-7 and other old browsers fall back to the more extreme pre which also includes nowrap and renders multiple spaces. Details on these and other settings (pre-wrap) at mozilla and css-tricks (thanks @Sablefoste).

While I'm generally averse to the S.O. predilection for second-guessing the question rather than answering it, in this case replacing newlines with <br> markup may increase vulnerability to injection attack with unwashed user input. You're crossing a bright red line whenever you find yourself changing .text() calls to .html() which the literal question implies would have to be done. (Thanks @AlexS for highlighting this point.) Even if you rule out a security risk at the time, future changes could unwittingly introduce it. Instead, this CSS allows you to get hard line breaks without markup using the safer .text().


you can simply do:

textAreaContent=textAreaContent.replace(/\n/g,"<br>");

Solution

Use this code

jQuery.nl2br = function(varTest){
  return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};

I wrote a little jQuery extension for this:

$.fn.nl2brText = function (sText) {
    var bReturnValue = 'undefined' == typeof sText;
    if(bReturnValue) {
        sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
    }
    var aElms = [];
    sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
        if(aElms.length) {
            aElms.push(document.createElement('br'));
        }
        aElms.push(document.createTextNode(sSubstring));
    });
    var $aElms = $(aElms);
    if(bReturnValue) {
        return $aElms;
    }
    return this.empty().append($aElms);
};

This JavaScript function considers whether to use insert or replace to handle the swap.

(Insert or replace HTML line breaks)

/**
 * This function is same as PHP's nl2br() with default parameters.
 *
 * @param {string} str Input text
 * @param {boolean} replaceMode Use replace instead of insert
 * @param {boolean} isXhtml Use XHTML 
 * @return {string} Filtered text
 */
function nl2br (str, replaceMode, isXhtml) {

  var breakTag = (isXhtml) ? '<br />' : '<br>';
  var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
  return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}

Demo - JSFiddle

JavaScript nl2br & br2nl functions


to improve @Luca Filosofi's accepted answer,

if needed, changing the beginning clause of this regex to be /([^>[\s]?\r\n]?) will also ingore the cases where the newline comes after a tag AND some whitespace, instead of just a tag immediately followed by a newline


Put this in your code (preferably in a general js functions library):

String.prototype.nl2br = function()
{
    return this.replace(/\n/g, "<br />");
}

Usage:

var myString = "test\ntest2";

myString.nl2br();

creating a string prototype function allows you to use this on any string.


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 line-breaks

HTML5 tag for horizontal line break Split string in JavaScript and detect line break Match linebreaks - \n or \r\n? How to linebreak an svg text within javascript? What is the difference between a "line feed" and a "carriage return"? Bash: Strip trailing linebreak from output How to read a file without newlines? How to break lines in PowerShell? How do I specify new lines on Python, when writing on files? How to remove line breaks (no characters!) from the string?