16

Possible Duplicate:
Replace all line break in a string with <br /> tag in javascript

How can I read the line break from a value with JavaScript and replace it with a <br /> tag?

Example:

var a = "This is man.
     Man like dog."

I would like my result to look something like

var a = "This is man.<br />Man like dog.";
Community
  • 1
  • 1
Jin Yong
  • 40,910
  • 71
  • 135
  • 181

3 Answers3

24
var newString=oldString.replace(/\n/g,"<br />");
nickf
  • 520,029
  • 197
  • 633
  • 717
Ali
  • 249,782
  • 257
  • 562
  • 750
10

To be complete: I've encountered cases where '\n' didn't work, in those cases I used:

someString.replace(/\n/g,'<br />')
          .replace(/\r/g,'<br />')
          .replace(/\r\n/g,'<br />');
KooiInc
  • 112,400
  • 31
  • 139
  • 174
6

+1 for Click Upvote's answer. I'd just point out that using that style of defining strings, you'll have a heap of extra whitespace in there. Doing a simple replace of the newline will actually give you this string:

"This is man.<br />     Man like dog."

The basic solution is to change your replace function:

newString = oldString.replace(/\n\s*/g, "<br />");

Or even better (IMHO), define your strings like this:

var a = "This is man.\n"
      + "Man like dog."
;

It means you can still get nice indenting without the extra overhead being added into your variables, plus, it allows you to add comments easily:

var a = "This is man.\n" // this is the first line.
      + "Man like dog."  // and woo a comment here too
;
nickf
  • 520,029
  • 197
  • 633
  • 717