29

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

7
  • He's doing the inverse of that, @GolezTrol Commented Nov 9, 2011 at 8:55
  • 1
    "Your<br>String".replace(/<br\s*\/?>/ig, "\r\n") Commented Nov 9, 2011 at 8:57
  • @Polynomial Yeah, you're right. Still the answer is to be found a dozen of times on SO. stackoverflow.com/questions/7672460/… Commented Nov 9, 2011 at 8:58
  • Indeed. He should've searched before posting. Commented Nov 9, 2011 at 8:59
  • 1
    stackoverflow.com/search?q=%5Bjavascript%5D+br+%5Cn Commented Nov 9, 2011 at 9:02

3 Answers 3

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"); } 
Sign up to request clarification or add additional context in comments.

3 Comments

PHP doesn't have a function called br2nl.
Haha, oops. Good catch. I meant the inverse of nl2br(). Though it really should have that function :(
Sometimes simple mistake happens like : Some one can use "</br>" , in this case use replace(/<\s*\/?br>/ig, "\r\n")
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!"

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.