我有一个小脚本,用于在每 4 个字符之后分割“var foo”内的文本。它运行良好。
但我的实际数据位于文本文件“a.txt”中。如何将整个文件文本放入“var foo”中。并将分割输出写入另一个文本文件?
var foo = "this is sample text !!!";
var arr = [];
for (var i = 0; i < foo.length; i++) {
if (i % 4 == 0 && i != 0)
arr.push(foo.substring(i - 4, i));
if (i == foo.length - 1)
arr.push(foo.substring(i - (i % 4), i+1));
}
document.write(arr);
console.log(arr);
要获取文件的内容,您需要使用输入标签选择文件。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="input" type="file" accept="text/plain">
<script src="script.js"></script>
</body>
读取文件内容的好时机是在更改事件中。
const input = document.querySelector("#input");
input.addEventListener("change", () => {
const file = input.files.item(0);
});
要将文件内容作为字符串读取,您需要对其进行转换。
function fileToText(file, callback) {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
callback(reader.result);
};
}
文件的内容作为字符串将可供回调函数使用。您可以创建一个链接并使用单击事件将字符串下载到文本文件中。
function save(content, fileName, mime) {
const blob = new Blob([content], {
tipe: mime
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
}
这是完整的代码
const input = document.querySelector("#input");
input.addEventListener("change", () => {
const file = input.files.item(0);
fileToText(file, (text) => {
save(text, "fileName.txt", "text/plain");
});
});
function fileToText(file, callback) {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
callback(reader.result);
};
}
function save(content, fileName, mime) {
const blob = new Blob([content], {
tipe: mime
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="input" type="file" accept="text/plain">
<script src="script.js"></script>
</body>
您可以在此处阅读有关在 JavaScript 中操作文件的更多信息:https://www.html5rocks.com/en/tutorials/file/dndfiles/ https://www.html5rocks.com/en/tutorials/file/dndfiles/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)