22

I am trying to replaces instances of \r or \n characters in my json object with <br /> for display on a website.

I tried:

myString = myString.replace("\\r?\\n", "<br />");

But this doesn't seem to do anything. When I replace the regex with something else (like "a" for instance, the replace works as expected). Any ideas why this isn't working for the newline chars?

jack
  • 223
  • 1
  • 2
  • 4

4 Answers4

51

Try this:

myString = myString.replace(/[\r\n]/g, "<br />");

Update: As told by Pointy on the comment below, this would replace a squence of \r\n with two <br />, the correct regex should be:

myString = myString.replace(/\r?\n/g, "<br />");
Pere
  • 1,647
  • 3
  • 27
  • 52
Felipe
  • 1,290
  • 10
  • 11
  • 4
    This will work, but it's probably **not** exactly what the OP wants. The almost-regex in the question is close: `/\r?\n/g` will replace any single line feed character *optionally* preceded by a carriage return character, with a single `
    `. Your regex, on the other hand, would replace a CR-LF sequence with **two** `
    ` tags.
    – Pointy Apr 14 '11 at 14:14
  • Oh yes, sorry. I've read "\r or \n" no the question, and didn't think about it. going to fix the answer, thanks. – Felipe Apr 14 '11 at 14:19
3

CSS:

 white-space: pre-wrap;

Is a far more eficient method.

2

try replace(/\r\n|\n/, '<br />')

Vlad Khomich
  • 5,820
  • 1
  • 27
  • 39
1

This worked for me:

str = str.replace(/\\n|\\r\\n|\\r/g, '<br/>');

Using double slash

Ricardo Ruwer
  • 549
  • 5
  • 9