Skip to content

Instantly share code, notes, and snippets.

@manh-dan
Forked from yidas/js-nl2br-br2nl.md
Created June 14, 2021 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manh-dan/2d0c0c4159291d20ea6edb75928e4bae to your computer and use it in GitHub Desktop.
Save manh-dan/2d0c0c4159291d20ea6edb75928e4bae 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

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