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