4

I am parsing the csv file in javascript using the below logic. The logic works correctly in firefox browser but on chrome browser, the output 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
  • check maybe you're not running scripts in chrome Commented Oct 12, 2016 at 6:05
  • Additionally you can call a get method inside a ready function Commented Oct 12, 2016 at 6:07
  • @claudios can you please let me know what does /\r\n+/g mean in javascript Commented Oct 12, 2016 at 6:15
  • 1
    .replace(/\r\n+/g, ",") replaces a CR followed with 1+ LF symbols with a comma multiple times. I guess it should have been written as .replace(/(?:\r?\n)+/g, ",") Commented Oct 12, 2016 at 6:52

1 Answer 1

2

The .replace(/\r\n+/g, ",") part of code replaces multiple occurrences of a CR followed with one or more LF symbols with a comma. E.g., it will replace with a comma "\r\n\n\n\n\n\n" or "\r\n", but will never find "\n\n\n\n".

Since linebreaks can be defined as CRLF, CR, LF, you may change that part to

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

to replace CRLF/LF/CR type of linebreaks.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.