1

I have a text file that generates values from a form like this,

First Name: John
Last Name: Doe

I also want to upload a file which I do with file input and read with a FileReader, I am able to get all of the contents of the text file, but I only want to get parts after ':' as, John and Doe so I can write it in a span as

Username: John Doe

Is there a way to only read and write the parts after ':'?

This is what I tried but it writes all the values including First Name and Last Name,

var reader = new FileReader();
reader.onload = function (event) {
  var contents = event.target.result;
  document.getElementById("username").innerHTML = contents;
};
reader.readAsText(file);
1
  • I doubt there being a way to extract the post-colon parts when reading, but processing the file after reading it is relatively easy. Commented Oct 30, 2019 at 12:33

2 Answers 2

2

You will have to read the entire file since you cannot know what its contents are or run any operation on it before it is read. To get the values after the : however, you can process the string you get

The below code assumes the string read will have lines seperated with \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);
Sign up to request clarification or add additional context in comments.

Comments

0

Have a look at this (assuming only one set in a 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.