Console.log not working when testing regex

风流意气都作罢 提交于 2021-02-11 16:45:18

问题


Can someone explain why my console log is not working?

Every time I select the file for verification to see if anything shows in the console nothing happens

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('The file cannot be used because its extension is not allowed!');
      return;
    } else {
      var file = this.files[0];

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


        // By lines
        var lines = this.result.split('\n');
        let N = /^(N1\d{14}.{78}|N9\d{14}.{14}\d{6})$/;

        for (var line = 0; line < lines.length; line++) {
          if (N.test(lines[line]) == N) {
            console.log("valid file");
          } else {
            console.log("invalid file");
          }
        }
      };
      reader.readAsText(file);
    }
    alert('file successfully validated!');
  }
});
<input type="file" id="file" />

EDIT

Could it be a problem in the conditional if (N.test(lines[line]) == N)?


回答1:


This appears to be a function context issue. Try changing var file = this.files[0]; to var file = document.getElementById("file").files[0];.

this can sometimes be tricky since its value is determined by how a function is called (runtime binding). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Edit: The conditional if (N.test(lines[line]) == N) is strange. The test() method executes a search for a match between a regular expression and a specified string and returns true or false. So, you don't need to compare the return of test to == N. Plus, you almost always want to use triple equals (===).




回答2:


Have you already check your conditions or try to place the console.log in various parts of your code? Maybe it's an issue with event firing. I've tried to run you regex with my console I guess it works smoothly.

regex result



来源:https://stackoverflow.com/questions/60101360/console-log-not-working-when-testing-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!