0

hello everyone I want to get the data line by line I have done it successfully now I want line by line plus word by word so I used this code

 var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(){
          var text = reader.result;
          var node = document.getElementById('output');
            node.innerText = text;
              var lines = this.result.split('\n');
         for(var line = 0; line < lines.length; line++){
            console.log(lines[line].split(" "));
          }
        };
        reader.readAsText(input.files[0]);
      };

the result is shocking in the console I am getting \r with the string enter image description here

kukab
  • 561
  • 5
  • 18
  • 1
    `var lines = this.result.split('\r\n');` –  May 14 '22 at 07:24
  • how do you know – kukab May 14 '22 at 07:27
  • The lines of Windows text files have both a \r (carriage **r**eturn) and a \n (**n**ewline) character at the end. You need to split using \r\n to get just the text of each line. –  May 14 '22 at 07:28

1 Answers1

0

I think you should not split('\r\n') as different OS'es use different character to end line.

From what I read in this post, Windows uses '\r\n', MacOS uses '\r' and Unix uses '\n'.

Since this is JavaScript, I assume you need an answer to cover most, if not all, possibilities. So, for a complete answer, I believe you should do the following.

let lines='';
if (navigator.userAgent.indexOf('Win')!=-1)
    lines = this.result.split('\r\n');
else if (navigator.userAgent.indexOf('Mac')!=-1)
    lines = this.result.split('\r');
else
    lines = this.result.split('\n');