js将txt文件中每行带有DTCode或是TxtID的的数据提取出来放到一个数组里
可以使用JavaScript的File API来读取本地的txt文件,然后使用正则表达式来匹配每行中包含DTCode或TxtID的数据,将其提取出来放入一个数组中。
以下是一个示例代码:
// 读取本地的txt文件
function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function(event) {
resolve(event.target.result);
};
reader.onerror = function(event) {
reject(event.target.error);
};
reader.readAsText(file);
});
}
// 提取每行中的DTCode或TxtID数据
function extractData(text) {
const lines = text.split('\n');
const regex = /(DTCode|TxtID):\s*(\w+)/;
const data = [];
lines.forEach(line => {
const match = line.match(regex);
if (match) {
const key = match[1];
const value = match[2];
data.push({ key, value });
}
});
return data;
}
// 处理文件选择事件
function handleFileSelect(event) {
const file = event.target.files[0];
readFile(file)
.then(text => {
const data = extractData(text);
console.log(data);
})
.catch(error => {
console.error(error);
});
}
// 监听文件选择事件
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', handleFileSelect);
在HTML中,需要使用一个<input type="file">元素来让用户选择txt文件,并给该元素添加一个id="file-input"的标识符。
<input id="file-input" type="file">
这样,当用户选择txt文件后,handleFileSelect函数会被触发,读取文件内容并提取出包含DTCode或TxtID的数据,然后将其打印到控制台上。你可以根据实际需求修改代码,将数据存储到数组中或进行其他操作。
原文地址: https://www.cveoy.top/t/topic/i9iW 著作权归作者所有。请勿转载和采集!