1

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?

Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
Amr Rady
  • 1,057
  • 1
  • 12
  • 24
  • 1
    insert more code – s.kuznetsov Aug 09 '20 at 16:17
  • What does *"avoid saving the copied text styling"* mean? Please provide a [mcve] with sample input and expected results – charlietfl Aug 09 '20 at 16:18
  • Is it this answer you are looking for: https://stackoverflow.com/questions/40417527/how-do-i-preserve-line-breaks-when-getting-text-from-a-textarea/40426477#:~:text=value.,HTML%20value%20will%20preserve%20newline. – Asutosh Aug 09 '20 at 16:18
  • @charlietfl https://stackoverflow.com/questions/63153738/how-to-insert-copied-text-to-textarea-without-styling – Amr Rady Aug 09 '20 at 16:19
  • https://stackoverflow.com/questions/20365465/extract-text-from-html-while-preserving-block-level-element-newlines – s.kuznetsov Aug 09 '20 at 16:20
  • Depends on how stripped down you need it. Could replace `
    ` with `\n\r` and then do the text conversion. Will lose automatic breaks from block elements. Another approach is parse all the elements and remove their attributes and save as html
    – charlietfl Aug 09 '20 at 16:59

2 Answers2

1

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 />');
Asaf
  • 1,446
  • 9
  • 17
  • I need the div so I can remove the styling from copied elements .. check https://stackoverflow.com/questions/63153738/how-to-insert-copied-text-to-textarea-without-styling – Amr Rady Aug 09 '20 at 18:28
0

I solved the problem by removing the function in the question stripHTML and adding this function as onPaste listener

onPaste(e) {
    e.preventDefault();
    const text = e.clipboardData.getData("text/plain");

    document.execCommand("insertText", false, text);
    return true;
}
Amr Rady
  • 1,057
  • 1
  • 12
  • 24