JavaScript replace \ n with <br/">
var messagetoSend = $.trim(document.getElementById("msgText").value); messagetoSend = messagetoSend.replace("\n", "<br />"); alert(messagetoSend); This entry:
Line 1 Line 2 Line 3 This is a warning:
Line 1<br /> Line 2 Line 3 When I expect him to warn:
Line 1<br /><br /><br />Line 2<br /><br /><br /><br /><br />Line 3 +68
Tom Gullen Feb 22 2018-11-22T00: 00Z
source share3 answers
You need / g for global matching
replace(/\n/g, "<br/>");
This works for me \n - see this answer if you have \r\n
NOTE Doupe 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 that some visitors to this question have intermittent text like
some text \ r \ n over more than one line "
In this case, you need to avoid the slash:
replace(/\\r\\n/g, "<br/>");
NOTE. All browsers will ignore \r in the line when rendering.
+155
mplungjan Feb 22 '11 at 9:45 2011-02-22 09:45
source shareHandles any type of line break
str.replace(new RegExp('\r?\n','g'), '<br />'); +70
WSkinner Nov 21 '13 at 19:14 2013-11-21 19:14
source shareUse regex for .replace() .:
messagetoSend = messagetoSend.replace(/\n/g, "<br />"); If these lines were made using Windows encoding, you will also have to replace carriage return .
messagetoSend = messagetoSend.replace(/\r\n/g, "<br />"); +7
jAndy Feb 22 '11 at 9:45 2011-02-22 09:45
source share