Javascript jQuery 将换行符转换为 br(nl2br 等效)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2919337/
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
jQuery convert line breaks to br (nl2br equivalent)
提问by gbhall
I'm having jQuery take some textarea content and insert it into an li.
我让 jQuery 获取一些 textarea 内容并将其插入到 li 中。
I want it to visually retain the line breaks.
我希望它在视觉上保留换行符。
There must be a really simple way to do this...
必须有一个非常简单的方法来做到这一点......
回答by Luca Filosofi
demo:http://so.devilmaycode.it/jquery-convert-line-breaks-to-br-nl2br-equivalent
演示:http : //so.devilmaycode.it/jquery-convert-line-breaks-to-br-nl2br-equivalent
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, ''+ breakTag +'');
}
回答by mck89
you can simply do:
你可以简单地做:
textAreaContent=textAreaContent.replace(/\n/g,"<br>");
回答by jnl
Put this in your code (preferably in a general js functions library):
把它放在你的代码中(最好放在一个通用的 js 函数库中):
String.prototype.nl2br = function()
{
return this.replace(/\n/g, "<br />");
}
Usage:
用法:
var myString = "test\ntest2";
myString.nl2br();
creating a string prototype function allows you to use this on any string.
创建字符串原型函数允许您在任何字符串上使用它。
回答by Bob Stein
In the spirit of changing the renderinginstead of changing the content, the following CSS makes each newline behave like a <br>:
本着更改渲染而不是更改内容的精神,以下 CSS使每个换行符的行为类似于<br>:
white-space: pre;
white-space: pre-line;
Why two rules: pre-lineonly affects newlines (thanks for the clue, @KevinPauli). IE6-7 and other old browsers fall back to the more extreme prewhich also includes nowrapand renders multiple spaces. Details on these and other settings (pre-wrap) at mozillaand css-tricks(thanks @Sablefoste).
为什么有两条规则:pre-line只影响换行符(感谢提供线索,@KevinPauli)。IE6-7 和其他旧浏览器退回到更极端的情况pre,它也包含nowrap并呈现多个空间。有关mozilla和css-tricks 中这些和其他设置 ( pre-wrap) 的详细信息(感谢 @Sablefoste)。
While I'm generally averse to the S.O. predilection for second-guessing the questionrather than answering it, in this case replacing newlines with <br>markup may increase vulnerability to injection attackwith unwashed user input. You're crossing a bright red line whenever you find yourself changing .text()calls to .html()which the literal question implies would have to be done. (Thanks @AlexS for highlighting this point.) Even if you rule out a security risk at the time, future changes could unwittingly introduce it. Instead, this CSS allows you to get hard line breaks without markup using the safer .text().
虽然我通常不喜欢对问题进行二次猜测而不是回答问题,但在这种情况下,用<br>标记替换换行符可能会增加对未经清洗的用户输入进行注入攻击的脆弱性。每当您发现自己更改了字面问题暗示必须完成的.text()呼叫时,您就会越过一条明亮的红线.html()。(感谢@AlexS 强调这一点。)即使您当时排除了安全风险,未来的更改也可能会在不知不觉中引入它。相反,此 CSS 允许您使用更安全的.text().
回答by Ata ul Mustafa
Solution
解决方案
Use this code
使用此代码
jQuery.nl2br = function(varTest){
return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};
回答by Nick Tsai
This JavaScript function considers whether to use insert or replace to handle the swap.
这个 JavaScript 函数会考虑是使用插入还是替换来处理交换。
(Insert or replace HTML line breaks)
(插入或替换 HTML 换行符)
/**
* This function is same as PHP's nl2br() with default parameters.
*
* @param {string} str Input text
* @param {boolean} replaceMode Use replace instead of insert
* @param {boolean} isXhtml Use XHTML
* @return {string} Filtered text
*/
function nl2br (str, replaceMode, isXhtml) {
var breakTag = (isXhtml) ? '<br />' : '<br>';
var replaceStr = (replaceMode) ? ''+ breakTag : ''+ breakTag +'';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}
回答by Andreas Otto
I wrote a little jQuery extension for this:
我为此编写了一个小的 jQuery 扩展:
$.fn.nl2brText = function (sText) {
var bReturnValue = 'undefined' == typeof sText;
if(bReturnValue) {
sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
}
var aElms = [];
sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
if(aElms.length) {
aElms.push(document.createElement('br'));
}
aElms.push(document.createTextNode(sSubstring));
});
var $aElms = $(aElms);
if(bReturnValue) {
return $aElms;
}
return this.empty().append($aElms);
};
回答by phlare
to improve @Luca Filosofi's accepted answer,
改进@Luca Filosofi 接受的答案,
if needed, changing the beginning clause of this regex to be /([^>[\s]?\r\n]?)will also ingore the cases where the newline comes after a tag AND some whitespace, instead of just a tag immediately followed by a newline
如果需要,将这个正则表达式的开始子句更改为/([^>[\s]?\r\n]?)也将忽略换行符出现在标记和一些空格之后的情况,而不仅仅是一个标记紧跟一个换行符
回答by Volo
Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerTextproperty that represents the renderedtext content of a node and its descendants.
从 DOM 中的 textarea 插入文本并保留换行符的另一种方法是使用Node.innerText属性,该属性表示节点及其后代的呈现文本内容。
As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.
作为一个 getter,它近似于用户使用光标突出显示元素的内容然后复制到剪贴板时获得的文本。
The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.
该属性在 2016 年成为标准,并得到现代浏览器的良好支持。我可以使用吗:当我发布此答案时,全球覆盖率达到 97%。

