Skip to content

Instantly share code, notes, and snippets.

@yidas
Last active September 29, 2023 05:26
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save yidas/41cc9272d3dff50f3c9560fb05e7255e to your computer and use it in GitHub Desktop.
Save yidas/41cc9272d3dff50f3c9560fb05e7255e to your computer and use it in GitHub Desktop.
JavaScript nl2br & br2nl functions

JavaScript nl2br & br2nl functions

The exchange of new line & br HTML tag could refer to PHP - nl2br() function, which uses to inserts HTML line breaks before all newlines in a string.

These JavaScript functions consider whether to use insert or replace to handle the swap.

nl2br

/**
 * 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);
}

br2nl

/**
 * This function inverses text from PHP's nl2br() with default parameters.
 *
 * @param {string} str Input text
 * @param {boolean} replaceMode Use replace instead of insert
 * @return {string} Filtered text
 */
function br2nl (str, replaceMode) {   
	
  var replaceStr = (replaceMode) ? "\n" : '';
  // Includes <br>, <BR>, <br />, </br>
  return str.replace(/<\s*\/?br\s*[\/]?>/gi, replaceStr);
}

Generally, most Front-End development doesn't require nl2br/br2nl functions. For example, if you're processing multiple lines of plain text output to <div>, you could add white-space style with pre-line or white-space: pre-wrap to the <div> for handling \n.

// jQuery for example
$("div").css('white-space', 'pre-wrap')
  .text('First Line\nSecond Line\n    ---End');

Demo - JSFiddle

JavaScript HTML Entities Encode & Decode

CSS - white-space for textarea print by MDN

@AnechaS
Copy link

AnechaS commented Jul 3, 2021

Thank you very much

@megaxorg
Copy link

megaxorg commented Jan 7, 2022

Thank you :-)

@Ethic-Pc
Copy link

Thank you !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment