Answers:
现在是2015年。此问题的正确答案是使用CSS white-space: pre-line或white-space: pre-wrap。干净优雅。支持该对的IE的最低版本是8。
https://css-tricks.com/almanac/properties/w/whitespace/
PS 在CSS3变得常见之前,您可能需要手动修剪初始和/或尾随空格。
new Date("2016");
如果将jQuery对象存储在变量中,则可以执行以下操作:
var obj = $("#example").text('this\n has\n newlines');
obj.html(obj.html().replace(/\n/g,'<br/>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
如果愿意,还可以创建一个函数来通过一个简单的调用来执行此操作,就像jQuery.text()那样:
$.fn.multiline = function(text){
this.text(text);
this.html(this.html().replace(/\n/g,'<br/>'));
return this;
}
// Now you can do this:
$("#example").multiline('this\n has\n newlines');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
这是我用的:
function htmlForTextWithEmbeddedNewlines(text) {
var htmls = [];
var lines = text.split(/\n/);
// The temporary <div/> is to perform HTML entity encoding reliably.
//
// document.createElement() is *much* faster than jQuery('<div></div>')
// http://stackoverflow.com/questions/268490/
//
// You don't need jQuery but then you need to struggle with browser
// differences in innerText/textContent yourself
var tmpDiv = jQuery(document.createElement('div'));
for (var i = 0 ; i < lines.length ; i++) {
htmls.push(tmpDiv.text(lines[i]).html());
}
return htmls.join("<br>");
}
jQuery('#div').html(htmlForTextWithEmbeddedNewlines("hello\nworld"));
text.split(/\\n/)或什至进行拆分text.split(/\\\\n|\\n|\n/)。我在通过带有将文字\n控件字符嵌入字符串中的API传递JSON格式的文本时遇到了此问题。
您可以使用 html替代text和取代的每次出现\n用<br>。您将不得不正确地转义您的文本。
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
text而此答案html直接使用。
我建议someElem直接使用该元素,因为用替换.html()也将替换字符串中的其他HTML标签。
这是我的功能:
function nl2br(el) {
var lines = $(el).text().split(/\n/);
$(el).empty();
for (var i = 0 ; i < lines.length ; i++) {
if (i > 0) $(el).append('<br>');
$(el).append(document.createTextNode(lines[i]));
}
return el;
}
致电方式:
someElem = nl2br(someElem);
<pre>在我看来,使用标签将其包装起来(并使用.html()而不是.text())是维护文本文件或纯文本中的换行符的最简单,最佳的解决方案(这由下面的Karim的答案建议)。但是:较新的替代方法是white-space: pre-wrap;按照cleong的答案中的建议使用