nl2br equivalent JavaScript function

nl2br equivalent JavaScript function

PHP provides a useful function nl2br that inserts HTML line breaks before all newlines \n in a string. Many times we want to utilize this functionality in JavaScript, although there is no nl2br  equivalent JavaScript function but we can create a custom function using regular expressions. Below is JavaScript equivalent for nl2br.

function nl2br(str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />'	: '<br>';
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag	+ '$2');

Author: Tahir Yasin

Tahir is a Passionate Web Developer from Lahore, Pakistan and a guy with NEVER-STOP-LEARNING attitude who keeps an eye on emerging technologies and customer trends.

2 thoughts on “nl2br equivalent JavaScript function”

  1. I have a textarea control in my php/mysql based web site and it allow the user to enter text
    as this
    then I write info in mysql database, but when I read and show information in a TD on another page, the line return are lost and all the text is on a single line.

    Can you help me with this ?
    Do you need more detail to help me?

    Thanks a lot !

Leave a Reply

Your email address will not be published. Required fields are marked *