jack
jack

Reputation: 233

Replacing newline character in javascript

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?

Upvotes: 23

Views: 61606

Answers (4)

Christian Pastor Cruz
Christian Pastor Cruz

Reputation: 376

CSS:

 white-space: pre-wrap;

Is a far more eficient method.

Upvotes: 3

Ricardo Ruwer
Ricardo Ruwer

Reputation: 589

This worked for me:

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

Using double slash

Upvotes: 1

Felipe
Felipe

Reputation: 1300

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 />");

Upvotes: 52

Vlad Khomich
Vlad Khomich

Reputation: 5880

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

Upvotes: 2

Related Questions