Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace \n with <br /> [duplicate]

var messagetoSend = $.trim(document.getElementById("msgText").value); messagetoSend = messagetoSend.replace("\n", "<br />"); alert(messagetoSend); 

Given input:

Line 1   Line 2     Line 3 

This alerts:

Line 1<br />   Line 2     Line 3 

When I expect it to alert:

Line 1<br /><br /><br />Line 2<br /><br /><br /><br /><br />Line 3 
like image 484
Tom Gullen Avatar asked Feb 22 '11 09:02

Tom Gullen


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. The pattern /g checks across all the string occurrences.

Can we use \n 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

You need the /g for global matching

replace(/\n/g, "<br />");

This works for me for \n - see this answer if you might have \r\n

NOTE: The dupe is the most complete answer for any combination of \r\n, \r or \n

var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");  console.log(messagetoSend);
<textarea id="x" rows="9">      Line 1                  Line 2                              Line 3  </textarea>

UPDATE

It seems some visitors of this question have text with the breaklines escaped as

some text\r\nover more than one line"

In that case you need to escape the slashes:

replace(/\\r\\n/g, "<br />");

NOTE: All browsers will ignore \r in a string when rendering.

like image 104
mplungjan Avatar answered Sep 23 '22 03:09

mplungjan