How can I replace HTML <BR> <BR/> or <BR /> with new line character "\n"
3 Answers
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"); } 3 Comments
mercator
PHP doesn't have a function called
br2nl.Polynomial
Haha, oops. Good catch. I meant the inverse of
nl2br(). Though it really should have that function :(eegloo
Sometimes simple mistake happens like : Some one can use "</br>" , in this case use replace(/<\s*\/?br>/ig, "\r\n")
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)
"Your<br>String".replace(/<br\s*\/?>/ig, "\r\n")