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
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\nNOTE: The dupe is the most complete answer for any combination of
\r\n,\ror\nUPDATE
It seems some visitors of this question have text with the breaklines escaped as
In that case you need to escape the slashes:
replace(/\\r\\n/g, "<br />");NOTE: All browsers will ignore
\rin a string when rendering.