转换 HTML 编码的 < br/ > 在 jquery .text() 中为 html 新行标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14426079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:33:49  来源:igfitidea点击:

Convert HTML-encoded &lt; br/ &gt; to html new line tag in jquery .text()

jqueryhtmlnewline

提问by user961627

I have some text in a variable sometextwhich I want to assign to divusing $('div').text(sometext);. The problem is that all <br/>s in sometextturn into &lt; br/ &gt;. I cannot use $('div').html()because there's a lot of internal structure that I want to retain within the div, so I can only use the .text()function.

我在一个变量中有一些文本sometext,我想分配给divusing $('div').text(sometext);。问题是所有的<br/>s 都sometext变成了&lt; br/ &gt;. 我无法使用,$('div').html()因为我想在 中保留很多内部结构div,所以我只能使用该.text()功能。

So once I've passed the text over the to the div, is there any way to change the encoded <br/>tag into a real line break in HTML? I mean something like this:

因此,一旦我将文本传递给div,有没有办法将编码的<br/>标签更改为HTML 中的真正换行符?我的意思是这样的:

$('div').convertMyBRsToHTML();

回答by axel.michel

Your requested function should look like this:

您请求的函数应如下所示:

$.fn.convertMyBRsToHTML = function(text){
    this.text(text);
    this.html(this.html().replace(/&lt;br\s*\/&gt;/g,'<br/>'));
    return this;
}

Now you could use by:

现在您可以通过以下方式使用:

$(YOUR_SELECTOR).convertMyBRsToHTML("<b>Some</b> new text.<br />next line<br />and so on");

回答by SLaks

You can replace the <br>s before setting the text:

您可以<br>在设置文本之前替换s:

$('div').text(sometext.replace(/<br\s*\/?>/gi, '\n');