How can I replace HTML <BR> <BR/> or <BR />
with new line character "\n"
Asked
Active
Viewed 5.9k times
28

Michael Rovinsky
- 6,807
- 7
- 15
- 30

Anoop
- 23,044
- 10
- 62
- 76
3 Answers
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,947
- 8
- 23

Polynomial
- 27,674
- 12
- 80
- 107
-
2
-
6Haha, oops. Good catch. I meant the inverse of `nl2br()`. Though it really *should* have that function :( – Polynomial Nov 09 '11 at 09:13
-
1Sometimes simple mistake happens like : Some one can use "" , in this case use replace(/<\s*\/?br>/ig, "\r\n") – eegloo Nov 11 '13 at 10:24
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
- 907
- 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)

Nick Tsai
- 3,799
- 33
- 36
String".replace(/
/ig, "\r\n")` – GolezTrol Nov 09 '11 at 08:57
with \n](http://stackoverflow.com/questions/5959415/jquery-javascript-regex-replace-br-with-n) (includes answers that do not involve jQuery) – mercator Nov 09 '11 at 09:09