Estoy usando esta respuesta para quitar HTML del texto.
Así es como funciona:
function strip(html){ let doc = new DOMParser().parseFromString(html, 'text/html'); return doc.body.textContent || ""; }Si tengo algo de HTML como este:
This is the first line<br> This is the second line<br> This is the third lineElimina los saltos de línea y crea un texto como este:
This is the first lineThis is the second lineThis is the third linePero como puede ver cuando elimina los saltos de línea, no queda espacio entre cada oración. No es así como quiero que se vea.
¿Cómo retengo un espacio entre cada línea (u oración) después de que elimina el HTML?
Quiero que se vea algo como esto:
This is the first line This is the second line This is the third lineSí, eso es posible, pero tendrías que manipular el documento antes de obtener el contenido del texto:
let doc = new DOMParser().parseFromString('This is the first line<br>\ This is the second line<br>\ This is the third line', 'text/html'); console.log(doc.body.textContent); doc.body.querySelectorAll('br') // Get all <br> elements .forEach(br => br.after(doc.createTextNode(' '))); // And spaces after them console.log(doc.body.textContent); Estoy usando querySelectorAll para obtener todos los saltos de línea y luego agrego un nodo de texto de espacio después de cada uno.