Find a string

Asked

Viewed 54 times

1

I have the following Javascript function:

document.addEventListener("DOMContentLoaded", function(){
  document.getElementById('file').onchange = function() {

  var extPermitidas = ['txt'];
  var extArquivo = this.value.split('.').pop();

  if(typeof extPermitidas.find(function(ext){ return extArquivo == ext; }) == 'undefined') {
    alert('O arquivo não pode ser validado pois possui extenção não permitida!');
    return;
  } else {
    var file = this.files[0];

    var reader = new FileReader();
    reader.onload = function(progressEvent){


      // By lines
      var lines = this.result.split('\n');
      for(var line = 0; line < lines.length; line++){
          console.log(lines[line]);
      }
    };
    reader.readAsText(file);
  }
  alert('Arquivo validado com sucesso!');
}});

If I have a file with lines more or less like this:

N3019283746536 9938 ANYTHING
N41092832938 01982108 81902

And I wish for example to check if your first 2 elements are N3 if your line size has 32 characters, how would I do that?

1 answer

3


You can do it with the method .susbtr(0,2) (first two characters) and with .length (returns the string size).

Seria:

if(lines[line].substr(0,2) == "N3" && lines[line].length == 32){
   // atendeu às condições
}

Note that I used the operator && which make the two conditions of if.

  • It means that if I needed valid N4 and N3 I would need to put N4 in the same if?

  • Because each N has a number of different characters, this would change to something like: if( (Lines[line]. substr(0,2) == "N3" && Lines[line]. length == 32 ) || (Lines[line]. substr(0,2) == "N4" && Lines[line]. lenght == 30), for example?

  • 1

    Only one was missing ) at the end to close the if: if( (lines[line].substr(0,2) == "N3" && lines[line].length == 32 ) || (lines[line].substr(0,2) == "N4" && lines[line].lenght == 30) ){

  • Why the substr is (0,2) and not (0,1)?

  • You want to get the first 2 characters. The 0,1 will only take the first.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.