Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \n with <br> and \r\n with <p> in javascript

I need JS that will remove any HTML tags, and then replace newlines with </p><p> and line breaks with <br/>. The string value is coming from a textarea and I understand Linux, Mac and Windows all format newlines differently so I need to take that into account. Thanks!

like image 373
rich Avatar asked Mar 05 '10 21:03

rich


People also ask

How do I replace all line breaks in a string with br /> elements?

The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks.

How do you replace a line break in a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

What is the equivalent of Br in JavaScript?

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.


1 Answers

\n and \r\n are equivalent. Linux uses the former, Windows uses the latter.

What you want to do is replace all cases of \n\n and \r\n\r\n with <p></p> and case of simply \n or \r\n with <br />

result = "<p>" + text + "</p>";
result = result.replace(/\r\n\r\n/g, "</p><p>").replace(/\n\n/g, "</p><p>");
result = result.replace(/\r\n/g, "<br />").replace(/\n/g, "<br />");

This assumes there is no html in your text.

like image 155
Joel Avatar answered Sep 26 '22 01:09

Joel