2

I'm uploading and then reading the CSV file but I'm facing an issue while splitting it, so basically, column names in CSV contain ',' so when I'm going to split the columns with ',' so I don't get the full column value, please suggest me some proper way for it. Thanks

const readCsv = (file) => {
 const reader = new FileReader();
 const filetext = reader.readAsBinaryString(file);
 reader.addEventListener('load', function (e) {
 const data = e.target.result;
 let parsedata = [];
 let newLinebrk = data.split('\n');
 for (let i = 0; i < newLinebrk.length; i++) {
 parsedata.push(newLinebrk[i].split(','));
 }
 console.log("parsedData: ", parsedata);
 });
};

CSV:

column 1 column2 
test lorem, ipsum, dummy/text

after splitting:

['test', 'lorem', 'ipsum', 'dummy/text']

so by doing that I'm unable to get a proper column name that contains a comma in string.

asked Jan 21, 2022 at 12:40
8
  • May I know if exploring existing solutions, such as csv-reader, can be considered? Also, is it okay to consider changing the delimiter to some other character (may be ^ or ~) instead of comma? Commented Jan 21, 2022 at 12:45
  • 1
    @jsN00b don't wanna use any 3rd party library Commented Jan 21, 2022 at 12:47
  • Issue is that within the code, how does one differentiate which comma is the delimiter (indicating end of a column) and which comma is part of the cell (text)? Commented Jan 21, 2022 at 12:49
  • yes, that is my question :) Commented Jan 21, 2022 at 12:50
  • @jsN00b can you share an example in react with csv-reader? Commented Jan 21, 2022 at 12:57

1 Answer 1

3

In my case, I used Papa Parse which fulfills my all requirements.

const readCsv = (file) => {
 const reader = new FileReader();
 reader.readAsBinaryString(file);
 reader.addEventListener('load', function (e) {
 const data = e.target.result;
 Papaparse.parse(data, {
 complete: function (results) {
 console.log("results: ", results.data);
 },
 });
 });
};
answered Jan 21, 2022 at 13:33
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.