在粘贴到文本区域时保留javascript字符串的换行符

Preserve line breaks from javascript string on paste into textarea

本文关键字:javascript 保留 字符串 换行符 区域 文本      更新时间:2023-09-26

在SE上看到类似的问题,但没有答案。

如果我单击代码中的按钮,我警告字符串,并且在警告中使用换行符对其进行格式化。当字符串被粘贴到文本区时,所有的换行符都被删除。

function pasteText() {
    
  var theText = "a'nb'nc";
  alert(theText);
  document.getElementById("theText").innerText = theText;
}
<textarea id="theText"></textarea>
<br><button onclick="pasteText()">Click</button>

注意:这只在Firefox中存在

  1. 使用textContent代替innerText

参见下面的代码片段

function pasteText() {
    
  var theText = "a'nb'nc";
  alert(theText);
  document.getElementById("theText").textContent = theText;
}
<textarea id="theText"></textarea>
<br><button onclick="pasteText()">Click</button>

  • 或innerHTML
  • function pasteText() {
        
      var theText = "a'nb'nc";
      alert(theText);
      document.getElementById("theText").innerHTML = theText;
    }
    <textarea id="theText"></textarea>
    <br><button onclick="pasteText()">Click</button>