如何在javascript中应用换行符

时间:2014-06-09 20:46:56

标签: javascript html css

我有一个从数据库中检索的javascript对象属性。

它有类似

的东西
This is line one
This is line two
This is line three
This is the line four

我的问题是,当我想在我的html页面中显示它们时,没有断线并且它们都像以下一样抽筋:

this is line one this is line two this is line three this is the line four

无论如何,我只能用Javascript显示换行符吗?

感谢。

6 个答案:

答案 0 :(得分:4)

将新行(\n)替换为<br>代码:

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

请参阅JSFiddle上的示例。

答案 1 :(得分:2)

换行符只是在HTML中处理为空格。

您可以在<pre>标记中显示字符串,然后将换行符用作换行符。

您可以使用<br>代码替换换行符:

s = s.replace(/(\r\n|\r|\n)/g, '<br>');

答案 2 :(得分:1)

在行之间插入<br />

答案 3 :(得分:1)

如果您要将此内容添加到HTML文档中,<br />应该有效。但在only-JS解决方案中,您应该将\r\n用于CRLF。

答案 4 :(得分:1)

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

这是极端情况,只适用于此示例。

答案 5 :(得分:1)

赔率是您的数据库使用换行符存储数据。

因为在野外使用了三个不同的换行符,我倾向于选择一个适用于所有三个换行符的过程。

var line="MSDOS line end\r\nUnix line end\nOld Mac line end\r";
var converted = line.replace(/\r\n|\r|\n/g, "<br>");