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.