nl2br and br2nl JavaScript/jQuery

HTML ignores whitespace, including new lines. In order to display paragraphs properly and not in a continuous block (for example when saving text from a texarea or retrieving it from a database) you have the following options:

  • Save text with its HTML.
  • Change new lines to
    tags using nl2br().
  • Replace new lines with paragraph tags by creating a custom function.

The Simplest way is to use the PHP nl2br() function but, in some cases, you might need to perform this conversion at the browser side with Javascript/jQuery when dinamically loading data using AJAX, for instance.

Following is this pair of handy functions written as jQuery extensions.

nl2br jQuery extension

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

br2nl jQuery extension

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

These functions can be used like:

var result = $.nl2br("this\nwill\nbe\nmultiline");
var result = $.br2nl("this<br>will<br>be<br>multiline");

2 thoughts on “nl2br and br2nl JavaScript/jQuery

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s