I'm trying to use javascript to read a txt file with the contents in a CSV format, parse through it and load it into a single array so I can do math operations to it like (sum, average, standard deviation). I got as far as reading the textfile and I need help with parsing through it.
Thanks!
inputExample.txt
5,4,4,4,4
3,3,3,3,2
1,5,4,7,6
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="file" id="openFile" />
<br>
<pre id="fileContents"></pre>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
document.getElementById("openFile").addEventListener('change', function(){
var fr = new FileReader();
fr.onload = function(){
// document.getElementById("fileContents").textContent = this.result;
console.log(this.result);
}
fr.readAsText(this.files[0]);
})
-
1possible duplicate: stackoverflow.com/a/12289296/1743938Christian Zosel– Christian Zosel2016年11月09日 19:59:09 +00:00Commented Nov 9, 2016 at 19:59
2 Answers 2
var arr = this.result.split(',');
If your content is also separated by new lines as your example you could replace them with commas and then split them.
var arr = this.result.replace(/\n/g, ',').split(',');
Comments
This is quite a common question. You can use regular expression or string operations.
This one uses regular expression:
// I am assuming your file has newline and carriage return, depending on your file format, it may have either of them or both of them
var foo = "5,4,4,4,4\n\r3,3,3,3,2\n\r1,5,4,7,6";
var regex = /(\d)(?=,|\n\r?)?/g;
var arr = foo.match(regex);
console.log(arr); //[ '5', '4', '4', '4', '4', '3', '3', '3', '3', '2', '1', '5', '4', '7' ]
And this one uses string operation:
var foo = "5,4,4,4,4\n\r3,3,3,3,2\n\r1,5,4,7,6";
var arr = [];
foo = foo.split('\n\r').forEach(function(el){
el = el.split(',').forEach(x => arr.push(x));
});
console.log(arr); //[ '5', '4', '4', '4', '4', '3', '3', '3', '3', '2', '1', '5', '4', '7', '6' ]
Check this link about how to parse csv in detail.
How can I parse a CSV string with Javascript, which contains comma in data?