[英]How do I apply line break in javascript
我有一個從數據庫檢索的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
無論如何,我只能使用Java腳本顯示換行符嗎?
謝謝。
換行符只是在HTML中被視為空格。
您可以在<pre>
標記中顯示字符串,然后將換行符用作換行符。
您可以使用<br>
標簽替換換行符:
s = s.replace(/(\r\n|\r|\n)/g, '<br>');
<br />
之間插入<br />
如果要將其添加到HTML文檔中, <br />
應該可以使用。 但是在僅JS解決方案中,對於CRLF應該使用\\r\\n
。
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');
這是極端情況,僅適用於此示例。
奇怪的是,您的數據庫使用換行符存儲了數據。
因為在野外使用了三種不同的換行符,所以我傾向於選擇一種適用於所有三種的換行符。
var line="MSDOS line end\r\nUnix line end\nOld Mac line end\r";
var converted = line.replace(/\r\n|\r|\n/g, "<br>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.