tags:

views:

1016

answers:

3

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.";
+9  A: 
var newString=oldString.replace(/\n/g,"<br />");
Click Upvote
-1: If there is more than one line break, this will fail. In Javascript, you must use /pattern/g.
eyelidlessness
its been fixed since :)
Click Upvote
+3  A: 

+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
Upvoted for +1 to click upvote's answer
Click Upvote
See my comment on Click Upvote's answer.
eyelidlessness
@click, upvote +1 to your comment that you upvoted +1 because I upvoted +1 your answer.
nickf
@Nick, another +1 upvote to your comment because of [all of that]
Click Upvote
THIS IS FUN!!!!1`
nickf
+4  A: 

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
str.replace(/\r\n?/g, '<br />').replace(/\n/g, '<br />');To avoid converting \r\n to <br /><br />
eyelidlessness
@eyelidlessness (must be cumbersome, eyelidlessness): okay, let's settle on someString.replace(/\n|\r\n?/g,'<br />') then.
KooiInc