How to find exact RegExp and do this using constructor syntax?

2

I have an algorithm that takes multiple full paths of files and verifies that each of them is 'banned' by the server.

The var s of for refers to each of these paths and sets is an array with regular expressions to check.

The problem is that, for example, if I have 4 files named from aq, aq2, aq3 and aq4 and set in array I want to only probify aq and aq4, all will be probidios ... hence the term needs to be exact.

I also could not use Regex literal with value of sets[s] so I want to know how to do this using constructor syntax.

var sets = ['contatos/aq', 'contatos/aq4'];

for(var s=0; s < sets.length; s++) {
                var comst = 
               if( new RegExp(sets[s]).test(path_p) ) { // se arquivo for proibido pelo sets... 
                    if(testheader.test(read) && testfooter.test(read)){
                        read = read.replace(testheader, '');
                        read = read.replace(testfooter, '');
                        fs.writeFileSync(totxt, read);
                    }
                    fs.renameSync(totxt, path_p);
                    return false;
               }
           }
    
asked by anonymous 15.01.2015 / 23:53

1 answer

2

Depending on the information you specified in the comments, what you need is a seemingly like solution (Watch the comments in the code):

// SOLUÇÂO -----------------------------

// informe as extenções que serão ignoradas na comparação
var extensions_ignore = ['.ejs'];

// informe os arquivos que são negados/proibidos 
var proibidos = ['contatos/aq', 'contatos/aq1', 'contatos/aq4'];

// método de verificação se path é permitido 
var isPermitido = function(path_p){
    // faz um replace 
    path_p = replaceExtensionsIgnored(path_p);
    for(var s=0; s < proibidos.length; s++) {
        // verfica se o path termina com algum dos caminho proibidos
        if(path_p.endsWith(proibidos[s])) { 
            return false;
        }
    }
    // se passar por todos os caminho proibidos é por que está liberado, então retorna true
    return true;
};

// remove extensão ignora do caminho
var replaceExtensionsIgnored = function(path){
    for (var i = 0; i < extensions_ignore.length; i++){
        path = path.replace(extensions_ignore[i], "");
    }
    return path;
};

var test = function(path){    
    print(path + " : " + isPermitido(path));
};

var initTests = function(){
    // inicializa recursos (fallbacks)
    init();
    
    print("Iniciando Testes...")
    test('__dirname/pasta/subpasta/home/contatos/aq');
    test('__dirname/pasta/subpasta/home/contatos/aq2.ejs');
    test('__dirname/pasta/subpasta/home/contatos/aq3.ejs');
    test('__dirname/pasta/subpasta/home/contatos/aq4.ejs');
}

// -- Recursos extras -----

var init = function(){
      fallbacks();
}

// (Não relevante) metódo para printar resultado
var print = function(message){
    if (typeof window === 'undefined') {
        // se for node.js
        console.log(message);
    }else{
        // se for DOM        
        var p = document.createElement("p");
        p.textContent = "  >  " + message;
        document.body.appendChild(p);
    }
};

var fallbacks = function(){
     /* Fallbsack para manter o support ao metodo em todas as versões do javascript já que este método está em versão experiemntal : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith */
    
    if (!String.prototype.endsWith) {
      Object.defineProperty(String.prototype, 'endsWith', {
        value: function(searchString, position) {
          var subjectString = this.toString();
          if (position === undefined || position > subjectString.length) {
            position = subjectString.length;
          }
          position -= searchString.length;
          var lastIndex = subjectString.indexOf(searchString, position);
          return lastIndex !== -1 && lastIndex === position;
        }
      });
    }
};

// ------ init tests
initTests();
  

I also posted a parallel version of here in jsFiddle

     

I know this code does not cover all cases, but it's a path to the solution.

As per your review I tested here on node.js and the only error that occurred was in the print method, which did not find the document in node.js (since there is not), but only remembering that this method is irrelevant to solution, just to start the tests.

I changed the print() method to check and start on node.js and the DOM. Now this same code runs on node.js.

Here is an example online of the solution at node.js

    
16.01.2015 / 03:17