最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How do I apply line break in javascript - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Jun 9, 2014 at 20:46 FlyingCatFlyingCat 14.3k36 gold badges127 silver badges201 bronze badges 7
  • 2 What does your JS look like? – Adjit Commented Jun 9, 2014 at 20:47
  • just var string = obj.string. and obj.string has the contents I mentioned above – FlyingCat Commented Jun 9, 2014 at 20:48
  • how are you getting the data from the db into the page? – j08691 Commented Jun 9, 2014 at 20:48
  • 1 Are there any special character separating the content in between lines? Otherwise it will be impossible unless you get the data differently – Adjit Commented Jun 9, 2014 at 20:49
  • 2 If the value of obj.string contains line break characters, the containing element can be styled with white-space: pre-line to display them. How to preserve newlines when showing a text file with jQuery – Jonathan Lonowski Commented Jun 9, 2014 at 20:49
 |  Show 2 more ments

6 Answers 6

Reset to default 5

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

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

See example on JSFiddle.

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>');

insert a <br /> between the lines

If you're adding this to the HTML Document, <br /> should work. But in only-JS solutions, you should use \r\n for CRLF.

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.

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>");
发布评论

评论列表(0)

  1. 暂无评论