Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract HTML textContent without removing the line breaks <br/>?

I'm using this function to extract the Text from the Textareas in my project (to avoid saving the copied text styling in the database),

export const stripHTML = (text) => {
  // eslint-disable-next-line no-var
  var temporalDivElement = document.createElement("div");

  temporalDivElement.innerHTML = text;
  return temporalDivElement.textContent || temporalDivElement.innerText || "";
};

The problem is that now the user can't write any line breaks in the text. What is the best way to solve that so I get a clean text but with the line breaks?

like image 638
Amr Rady Avatar asked Nov 22 '25 10:11

Amr Rady


1 Answers

You don't need the div, just do this:

var textarea = document.getElementById('textarea');
var temporalDivElement = document.createElement("div");
temporalDivElement.innerHTML = textarea.value;
var tempText = temporalDivElement.textContent || temporalDivElement.innerText || "";
return tempText.replace(/\r?\n/g, '<br />');
like image 193
Asaf Avatar answered Nov 24 '25 22:11

Asaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!