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!
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.
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.
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.
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.
\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With