Scriptbaker
SCRIPTBAKERAI & Software Engineering
JavaScript

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 JavaS

· 5 min read

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

S

Scriptbaker Editorial Team

The Scriptbaker editorial team comprises engineers, AI specialists, and digital strategists based in Dubai and Rawalpindi. We write about software development, artificial intelligence, and digital transformation to help organisations build better products. Learn more about us →