114
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
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • given that the string is html and not plaintext just style it so that \n causes a line break, `white-space: pre;` otherwise you'll end up corruting entities that contain \n, if it's actually text, congrats you now own an XSS vuln. – Jasen Apr 14 '21 at 05:05

3 Answers3

222

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.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
102

Handles either type of line break

str.replace(new RegExp('\r?\n','g'), '<br />');
WSkinner
  • 2,147
  • 1
  • 19
  • 21
10

Use a regular expression for .replace().:

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

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");
jAndy
  • 231,737
  • 57
  • 305
  • 359