使用JavaScript读取CSV文本文件并将结果加载到数组中

3

我正在尝试使用JavaScript读取一个内容为CSV格式的txt文件,解析它并将其加载到一个单一数组中,以便我可以对其执行数学操作,如(求和、平均值、标准偏差)。我已经成功读取文本文件,现在需要帮助解析它。

谢谢!

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]);
})

1
可能重复:https://dev59.com/5ms05IYBdhLWcg3wIObS#12289296 - Christian Zosel
2个回答

2
var arr = this.result.split(',');

如果您的内容与您的示例一样也是由换行符分隔的,您可以将它们替换为逗号,然后再进行拆分。
var arr = this.result.replace(/\n/g, ',').split(',');

0
这是一个很常见的问题。您可以使用正则表达式或字符串操作。
这个例子使用正则表达式:
 // 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' ]

这个使用字符串操作:

 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' ]

请查看此链接,了解如何详细解析csv。

如何使用JavaScript解析包含数据逗号的CSV字符串?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接