I'm having jQuery take some textarea content and insert it into an li.
I want it to visually retain the line breaks.
There must be a really simple way to do this...
I'm having jQuery take some textarea content and insert it into an li.
I want it to visually retain the line breaks.
There must be a really simple way to do this...
demo: 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, '$1'+ breakTag +'$2');
}
(str+'').replace()
?? why not just str.replace()
? –
Caricaria <br/>
i fixed it by removing the $1
and $2
from return statement like this: return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, breakTag)
–
Algebra you can simply do:
textAreaContent=textAreaContent.replace(/\n/g,"<br>");
In the spirit of changing the rendering instead of changing the content, the following CSS makes each newline behave like a <br>
:
white-space: pre;
white-space: pre-line;
Why two rules: pre-line
only affects newlines (thanks for the clue, @KevinPauli). IE6-7 and other old browsers fall back to the more extreme pre
which also includes nowrap
and renders multiple spaces. Details on these and other settings (pre-wrap
) at mozilla and css-tricks (thanks @Sablefoste).
While I'm generally averse to the S.O. predilection for second-guessing the question rather than answering it, in this case replacing newlines with <br>
markup may increase vulnerability to injection attack with 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()
.
white-space:
options, such as pre-wrap
. See css-tricks.com/almanac/properties/w/whitespace –
Skip .html()
to set the content, which in turn would allow the user to insert arbitrary HTML unless you filter that out in advance. –
Merna .html()
danger @AlexS, tried to incorporate. –
Namedropper Put this in your code (preferably in a general js functions library):
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.
Solution
Use this code
jQuery.nl2br = function(varTest){
return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};
This JavaScript function considers whether to use insert or replace to handle the swap.
(Insert or replace HTML line breaks)
/**
* 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) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}
I wrote a little jQuery extension for this:
$.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);
};
to improve @Luca Filosofi's accepted answer,
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
Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.
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.
The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.
© 2022 - 2024 — McMap. All rights reserved.