Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing newline character in javascript

Tags:

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?

like image 858
jack Avatar asked Apr 14 '11 14:04

jack


1 Answers

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 />"); 
like image 147
Felipe Avatar answered Oct 15 '22 19:10

Felipe