28

How can I replace HTML <BR> <BR/> or <BR /> with new line character "\n"

Michael Rovinsky
  • 5,807
  • 7
  • 12
  • 28
Anoop
  • 22,496
  • 10
  • 60
  • 70

3 Answers3

59

You're looking for an equivilent of PHP's nl2br(). This should do the job:

function br2nl(str) {
    return str.replace(/<br\s*\/?>/mg,"\n");
}
Christoph Kluge
  • 1,844
  • 6
  • 22
Polynomial
  • 26,720
  • 10
  • 77
  • 106
1

A cheap function:

function brToNewLine(str) {
    return str.replace(/<br ?\/?>/g, "\n");
}

es.

vat str = "Hello<br \>world!";
var result = brToNewLine(str);

The result is: "Hello/nworld!"

Prais
  • 839
  • 9
  • 14
1

This function considers whether to remove or replace the tags such as <br>, <BR>, <br />, </br>.

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

In your case, you need to use replaceMode. For eaxmple: br2nl('1st<br>2st', true)

Demo - JSFiddle

JavaScript nl2br & br2nl functions

Nick Tsai
  • 3,437
  • 30
  • 34