首页 > 解决方案 > 如何让 JavaScript split() 方法通过新行正确拆分粘贴的文本?

问题描述

有人可以帮忙吗?

我有一些内容可编辑的 div 元素。我需要在其中添加复制/粘贴数字的选项。这些数字可以在列和行中,就像在 excel 中一样。

粘贴的文本必须先用换行符分割,然后每行再用空格/制表符分割,以便 div 元素中只有左上角的数字。其余的数字应该进入后续的 div 元素,就像在 excel 中一样。

const target = document.querySelector("div#input11");

target.addEventListener('paste', (event) => {

  let paste = (event.clipboardData || window.clipboardData).getData('text/plain');
  var pasteString = paste.toString();
  result = stringOperations(pasteString);

  const selection = window.getSelection();
  if (!selection.rangeCount) return false;
  selection.deleteFromDocument();
  selection.getRangeAt(0).insertNode(document.createTextNode(result));

  event.preventDefault();

});

function stringOperations(s) {

  var rowArray = s.split("/(\n\r|\n|\r)/gm");
  return rowArray[0];

}
<div id="input11" class="input-field2" contenteditable="true" onChange="checkInput(1,1)"></div>

问题是我的 RegEx 表达式似乎无法识别新行,因此他粘贴的文本不会被新行分割。

当我将其复制/粘贴到 div 中时:

44439 515 541 928
43936 929 692 711
44464 800 710 824
41533 979 675 758

我只是将数字作为一个长序列,用空格而不是第一行分隔。

44439 515 541 928 43936 929 692 711 44464 800 710 824 41533 979 675 758

我非常感谢任何帮助,谢谢。

标签: javascripthtml

解决方案


您的正则表达式有引号,而它不应该有引号。改为"/(\n\r|\n|\r)/gm"简单/(\n\r|\n|\r)/gm,你应该很高兴。

const target = document.querySelector("div#input11");

target.addEventListener('paste', (event) => {

  let paste = (event.clipboardData || window.clipboardData).getData('text/plain');
  var pasteString = paste.toString();
  result = stringOperations(pasteString);

  const selection = window.getSelection();
  if (!selection.rangeCount) return false;
  selection.deleteFromDocument();
  selection.getRangeAt(0).insertNode(document.createTextNode(result));

  event.preventDefault();

});

function stringOperations(s) {
  var rowArray = s.split(/(\n\r|\n|\r)/gm);
  return rowArray[0];
}
<div id="input11" class="input-field2" contenteditable="true" onChange="checkInput(1,1)"></div>


推荐阅读