jQuery text()和换行符


114

我想说

$(someElem).text('this\n has\n newlines);

并在浏览器中以换行符呈现。我发现的唯一解决方法是在someElem上将css属性“ white-space”设置为“ pre”。这几乎可以工作,但是即使我将padding设置为0,文本和someElem的顶部之间也会有一个非常大的填充。是否有办法摆脱这种情况?


2
<pre>在我看来,使用标签将其包装起来(并使用.html()而不是.text())是维护文本文件或纯文本中的换行符的最简单,最佳的解决方案(这由下面的Karim的答案建议)。但是:较新的替代方法是white-space: pre-wrap;按照cleong的答案中的建议使用
-edwardtyl

1
为什么不使用append()代替test()<br/>代替\n?像这样-$(someElem).append("this <br/> has <br/> newlines");
尔法恩艾哈迈德

Answers:


132

现在是2015年。此问题的正确答案是使用CSS white-space: pre-linewhite-space: pre-wrap。干净优雅。支持该对的IE的最低版本是8。

https://css-tricks.com/almanac/properties/w/whitespace/

PS 在CSS3变得常见之前,您可能需要手动修剪初始和/或尾随空格。


3
这应该是答案。
Axel

3
这就是答案。应该更高。欢迎来到2016年
neoRiley

3
在2017年发现了这一点:仍然相关,并且仍然是问题的答案。
特洛伊·哈里斯

6
这篇文章中有错误。年份是2017年,而不是2015年。其他所有内容看起来都很准确。
JDB仍然记得Monica

1
new Date("2016");
布兰迪托

60

如果将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>


第一个代码段的第二行中缺少缺少的右括号。
Mahmoud Fayez 2013年

1
这实际上回答了OP的问题
汤米

最好的,像魅力一样工作并解决了这个问题。
ZEESHAN ARSHAD

37

这是我用的:

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

1
实际上,它优于Mark的建议,因为它没有XSS攻击的风险。
安德鲁·B。

我认为您可以在函数之外创建div(即document.createElement('div')),并将其用于所有调用,对吗?
法比奥·扎德罗兹尼

@FabioZadrozny:是的,你是对的!我已经(几乎)编辑了答案。div是在函数内部但现在在循环外部创建的。它可能完全在函数之外,但是使用起来很麻烦。
Peter V.Mørch'12

1
我相信@cleong的答案是最好的解决方案
minillinim 2015年

如果您的文字中有明确的换行符,则可能要使用text.split(/\\n/)或什至进行拆分text.split(/\\\\n|\\n|\n/)。我在通过带有将文字\n控件字符嵌入字符串中的API传递JSON格式的文本时遇到了此问题。
D. Visser

20

或者,尝试使用.html,然后包装<pre>标签:

$(someElem).html('this\n has\n newlines').wrap('<pre />');

13

您可以使用 html替代text和取代的每次出现\n<br>。您将不得不正确地转义您的文本。

x = x.replace(/&/g, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

@Matthew Flaschen:谢谢,固定。
Mark Byers 2010年

7
阅读此答案的某些人可能不知道这有多危险。切勿将此解决方案与用户提供的文本一起使用。彼得·莫奇(PeterMørch)的解决方案更可取。
安德鲁·B。

1
@kulebyashik Peter的解决方案使用,text而此答案html直接使用。
约翰·肖

1

我建议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);

1
读者注意:如果您计划开发Firefox附加组件,则此答案特别有用。W3C和Mozilla不赞成innerHTML或(.html()(如果使用jQuery,则为.html()),并且上述代码对清除审阅过程非常有帮助。有关更多信息,请参阅安全性注意事项@ developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
Delicia Brummitt 2014年

1

试试这个:

$(someElem).html('this<br> has<br> newlines);

0

使用CSS空格属性可能是最好的解决方案。使用Firebug或Chrome开发者工具确定您看到的多余填充的来源。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.