简体   繁体   English

如何在不删除换行符的情况下提取 HTML textContent<br> ?

[英]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),我正在使用这个 function 从我项目中的 Textareas 中提取文本(以避免将复制的文本样式保存在数据库中),

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?解决这个问题的最佳方法是什么,所以我得到一个干净的文本但有换行符?

You don't need the div, just do this:您不需要 div,只需执行以下操作:

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 />');

I solved the problem by removing the function in the question stripHTML and adding this function as onPaste listener我通过删除问题 stripHTML 中的stripHTML并将此 function 添加为 onPaste 侦听器解决了这个问题

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

    document.execCommand("insertText", false, text);
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM