Reputation: 121
I am a beginner coder and looking to work with csv data retrieved using an api call and then splitting it into arrays. I want to chart the data so in order to plot it I need to remove the double quotes around the csv data. It comes in like this:
"2020-02-04","0.7531"
"2020-02-05","0.7525"
I need it to look like this:
2020-02-04,0.7531
2020-02-05,0.7525
This is the code. I tried playing around with var myStr = myStr.replace(/"/g, ''); in javasript but I can't seem to get it to work.
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('xxxxxxx.csv');
var data = await response.text();
var years = [];
var temps = [];
var rows = data.split('\n').slice(9);
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
temps.push(1 + parseFloat(cols[1]));
});
console.log (years, temps );
return { years, temps };
Upvotes: 1
Views: 4375
Reputation: 142
You are using the replace function a little bit wrong. This should work for you:
a = '"2020-02-04","0.7531"';
a= a.replace(/"/g, "");
The replace function has two arguments. The first argument '/"/g' specifies a Regular Expression. Everything that you put between the two slahes is searched for (in this case only "). The 'g' after the second slash symbolizes that they should not stop after the first match they found but look for all matches in the string.
The second argument specifies what you want all matches to be replaced with. In this case, that is nothing -> "" . But you could also go for a space for example (" ").
Good luck with your coding experience!
Upvotes: 0
Reputation: 505
(cols[0]).replace(/"/g, "") before years.push(cols[0]) statement will do, if you are only having problem with double quotes.
Upvotes: 0
Reputation: 943108
Don't try to write your own CSV parser.
If your data is simple, then you are wasting your time by reinventing the wheel.
If your data gets marginally complex, then you'll trip over the edge cases in the CSV data format design.
Pick an existing parser such as Papa Parse and use it instead. It knows how to deal with quotes around data (and quotes in the middle of data, and new lines etc etc etc).
const data = await response.text();
const results = Papa.parse(data);
const rows = results.data;
Upvotes: 1
Reputation: 1043
If you are sure the quotes are always there you can get rid of them using substring
let withoutQuotes = cols[i].substring(1, cols[i].length - 1)
Upvotes: 1