FlyingCat
FlyingCat

Reputation: 14250

How do I apply line break in javascript

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

Answers (6)

Jeremy J Starcher
Jeremy J Starcher

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

Guffa
Guffa

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

Jordan
Jordan

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

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

Replace new lines (\n) with <br> tags:

replace(/\n/g, '<br>');

See example on JSFiddle.

Upvotes: 5

Bruno Volpato
Bruno Volpato

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

Snappawapa
Snappawapa

Reputation: 2012

insert a <br /> between the lines

Upvotes: 1

Related Questions