问题描述
我正在尝试加载文本文件,逐行读取它,并将其显示在文本区域中。然后,我想使用此文本区域中的每一行创建一个新数组,以便以后可以以各种方式操作该数组(例如,根据每一行包含的内容来过滤内容)。
到目前为止,我已经获得它来逐行读取文本文件并将其显示在文本区域中,但是当我到达下面的注释部分时,我正在努力寻找如何将每一行推到新的位置数组。
let input = document.querySelector("input");
let textArea = document.querySelector("textarea");
let files = input.files;
input.addEventListener("change",() => {
let files = input.files;
if (files.length == 0) return;
const file = files[0];
let reader = new FileReader();
reader.onload = function (e) {
const file = e.target.result;
const lines = file.split(/\r\n|\n/);
const content = lines.join('\n');
textArea.value = content; //trying to create a new array out of each line in this text area
//Could I use a For loop here on each line of the textArea? I am having trouble accessing it line by line
reader.readAsText(file);
//I have tried accessing the content variable from here but it says it is undefined.
}
);
我在尝试访问函数外部的content
变量时遇到了麻烦。这与范围有关吗?
解决方法
您必须使用div而不是textarea
但是您添加了“ contenteditable = true”属性
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content
还要检查RegExp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp