在 JavaScript 中,有没有办法使用 FileReader 获取文件的特定部分?

Is there a way to get specific parts of a file with FileReader in JavaScript?

我有一个文本文件可以从这样的表单生成值,

First Name: John
Last Name: Doe

我还想上传一个文件,我用文件输入完成并用 FileReader 读取,我能够获取文本文件的所有内容,但我只想获取 ':' 之后的部分,因为, John 和 Doe 所以我可以把它写成

Username: John Doe

有没有办法只读写':'后面的部分?

这是我尝试过的方法,但它写入了所有值,包括名字和姓氏,

var reader = new FileReader();
reader.onload = function (event) {
  var contents = event.target.result;
  document.getElementById("username").innerHTML = contents;
};
reader.readAsText(file);

您将不得不阅读整个文件,因为在阅读之前您无法知道其内容或运行对其进行的任何操作。 但是,要在 : 之后获取值,您可以处理您获取的字符串

下面的代码假定读取的字符串将包含用 \n

分隔的行
var reader = new FileReader();
reader.onload = function (event) {
  var contents = event.target.result;
  var lines = contents.split('\n');
  var username = "";
  lines.forEach(line => {
    var [key, value] = line.split(':'); // splits the line into an array breaking on the colon
    if(key === 'First Name' || key === 'Last Name') { // checks for the keys so that any other key:value in subsequent lines will not be added to the username
        username = username + " " + value.trim() // to remove trailing whitespaces, if any, from the value
    }
  });
  document.getElementById("username").innerHTML = username;
};
reader.readAsText(file);

看看这个(假设一个文件中只有一组)

const file = `First name: John
            Last name: Doe`

const [match, fName, lName] = file.match(/: (\w+)\s.+: (\w+)\s?/)
document.getElementById("username").innerHTML = `${fName.trim()} ${lName.trim()}`;
<span id="username"></span>