Javascript csv parsing not working in chrome

I am parsing a csv file in javascript using the logic below. The logic works correctly in the Firefox browser, but in the Chrome browser, the result is different.

 var r = new FileReader();
 r.onload = function (e) {
   contents = e.target.result;
     $scope.$apply(function () {
       $scope.fileReader = contents;
        contents = contents.replace(/\r\n+/g, ",");
        reqObj.names = contents.split(",");
        defer.resolve("Succesfully executed");
     });
  };
r.readAsText(file);

Output in Firefox: names: ["pradeep", "naveen", "kiran"] Output in Chrome: names: ["pradeep \ nnaveen \ nkiran"]

Please let me know where I am going wrong.

+4
source share
1 answer

Part of the code .replace(/\r\n+/g, ",")replaces several occurrences of CR, followed by one or more LF semicolons. For example, it will replace a comma "\r\n\n\n\n\n\n"or "\r\n", but will never find "\n\n\n\n".

CRLF, CR, LF,

.replace(/(?:\r?\n|\r)+/g, ",")

CRLF/LF/CR.

var s = "pradeep\r\nnaveen\nkiran\rhere";
console.log(s.replace(/(?:\r?\n|\r)+/g, ","));
Hide result
+2

Source: https://habr.com/ru/post/1657463/


All Articles