javascript - 如何让 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
我非常感谢任何帮助,谢谢。
解决方案
您的正则表达式有引号,而它不应该有引号。改为"/(\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>
推荐阅读
- html - 具有平滑大小变化的边框
- java - 包装 JTextArea 没有获得足够的空间/窃取空间
- rest - 我如何知道我的 HERE 免费增值帐户的 aap_d、app_code?
- python - 以下递归函数代码所需的输出
- ada - 获取任务中的字段值
- python - Pygame 没有检测到 g29 轮的轴
- python - 如何在命令提示符下从 Scrapy 的输出中删除 \r\n?
- python - 在 python 列表中对午餐项目进行排序
- java - 与后端 API 交互
- ruby-on-rails - 如何解决: SQLException: no such table: locations: ALTER TABLE "locations" ADD "user_id" integer