jQuery: convert new lines to br

Replacing new lines with the br element is a required task that we need to perform especially when we want to normalize the default behavior of browsers with the innerHTML property. Browsers such as Internet Explorer, for instance, don't preserve new lines when they have to copy and reproduce the HTML content of an element. Characters such as \n or \r must therefore be converted into br before dealing with this HTML content. In this post I'm going to show you how to accomplish this task with jQuery.

All we need to do is to use the following regular expression with the JavaScript replace() function:

var nl = /\n|\r|\r\n/g;

Here's the jQuery code:


$(document).ready(function() {


  $('div').each(function() {

    var $pre = $(this);
    var html = $pre.html();
    
    var nl = /\n|\r|\r\n/g;
    
    $pre.html(html.replace(nl, '<br>'));

  });
});

You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: convert new lines to br”

  1. sometimes on blogspot if we write the script code on textarea method, there is always the code on the textarea <br />
    what this method can be used to textarea trick?

  2. Exactly! :-) The point, however, is that IE 8 - doesn't support this solution at the moment. I have to better check my regular expression pattern to make it select a new line in IE. I'll keep you informed. Thanks for the comment :-)

Leave a Reply

Note: Only a member of this blog may post a comment.