How can I replace HTML <BR> <BR/> or <BR />
with new line character "\n"
The <br> or <br /> tag is an HTML element that will display everything after this <br> or <br /> by starting from new line when rendered in browser while the \n is used to jump to next line in the source code or the output prompt in standard output.
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. The pattern /g checks across all the string occurrences.
Upon click of a button, we will replace the new line with new line character ( ) and display the result on the screen. Please have a look over the code example and the steps given below. We have 3 elements in the HTML file ( div, button, and h1 ). The div element is just a wrapper for the rest of the elements.
What the method does is to simply iterate through the lines in the input and add it to an ArrayList. After iterating through all of the lines (thus having split the input), the list elements are joined together with the <br />break line tag, effectively replacing the newline characters.
In today’s post, we will learn both the functions to replace newline ( ) with an HTML break tag ( <br/> ). The replaceAll () is an in-built method provided by JavaScript which takes the two input parameters and returns a new String in which all matches of a pattern are replaced with a replacement.
Replace (‘string’, ‘ ’, ”) will replace only the substring in the whole string. If the substring is not found, it’ll not replace anything and the flow will continue. To replace a new line you must use the right ‘new line’ character in your flow.
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"); }
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!"
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