Quiero poder decir
$(someElem).text('this\n has\n newlines);
y se muestra con nuevas líneas en el navegador. La única solución que he encontrado es establecer la propiedad css 'white-space' a 'pre' en someElem. Esto casi funciona, pero entonces tengo un molesto gran relleno entre el texto y la parte superior de algunosElem, incluso cuando se establece el relleno a 0. ¿Hay alguna manera de deshacerse de esto?
Esto es lo que yo uso:
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"));
Puede utilizar html
en lugar de text
y sustituir cada aparición de \n
por <br>
. Sin embargo, tendrás que escapar correctamente el texto.
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');