Reputation: 14250
I have a javascript object property that is retrieved from database.
It has something like
This is line one
This is line two
This is line three
This is the line four
My problem is when I want to show them in my html page, there is no break line and they are all cramp together like:
this is line one this is line two this is line three this is the line four
Is there anyway I can show the line break with Javascript only?
Thanks.
Upvotes: 1
Views: 2733
Reputation: 23863
Odds are your DB has the data stored with a line-break character.
Because there are three different line break characters used out in the wild, I tend to choose a process that will work on all three.
var line="MSDOS line end\r\nUnix line end\nOld Mac line end\r";
var converted = line.replace(/\r\n|\r|\n/g, "<br>");
Upvotes: 1
Reputation: 700342
Line breaks are just treated as spaces in HTML.
You can display the string in a <pre>
tag, then the line breaks are used as line breaks.
You can replace the line breaks with <br>
tags:
s = s.replace(/(\r\n|\r|\n)/g, '<br>');
Upvotes: 2
Reputation: 2039
var string = "this is line one this is line two this is line three this is the line four";
var stringNewLine = string.replace('this', '<br/>this');
This is an extreme edge case and will only work with this example.
Upvotes: 1
Reputation: 42048
Replace new lines (\n
) with <br>
tags:
replace(/\n/g, '<br>');
See example on JSFiddle.
Upvotes: 5
Reputation: 1428
If you're adding this to the HTML Document, <br />
should work. But in only-JS solutions, you should use \r\n
for CRLF.
Upvotes: 1