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

Asked

Viewed 174 times

2

I have an algorithm that takes several complete file paths and checks if each of them is 'forbidden' by the server.

The var s of for is related to each of these paths and the sets is an array with regular expressions to be checked.

The problem is that, for example, if I have 4 named files from aq, aq2, aq3 and aq4 and set in array that I want to probidir only the 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;
               }
           }
  • 2

    My impression, or is your code incomplete? What is this var comst = Loose there on the 4° line?

  • 1

    One-eyed here I touched a few things and did some tests and apparently simply is working, check if it helps you.

  • @Fernando I made a small mistake: the files are actually aq, aq2, aq3 and aq4. I’ve already edited. Understand why it has to be an exact Regex now?

  • 2

    When you say exact you say: 'contatos/aq' == 'contatos/aq'?

  • @Fernando that same.

  • Then do a simple check, no regular expression, of a look therein. That’s the way it is?

  • @Fernando It turns out that the complete paths are more or less like this: __dirname/folder/subfolder/home/contacts/aq.ejs

  • 1

    I did it the way you said it from one look here, if that is the case let me know that I have prepared a response explaining in more detail the solution.

Show 3 more comments

1 answer

2


According to information you specified in the comments, what you need is a solution apparently as is (Follow 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 the code here in jsFiddle

I know that code doesn’t cover every case, but it’s a path option to the solution.

As your comment tested here on Node.js and only error that occurred was in the method print, that did not find the Document in Node.js (since there is not), but only remembering that this method is irrelevant to the solution, it is only to print the tests.

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

Here is an online example of the solution in Node.js

  • Thanks, man. But on my Ode it didn’t work. Anyway I’m giving up on what I was gonna do.

  • Okay. But if you haven’t solved your problem, don’t mark it as an answer (I’m glad you scored, I get points for it, but I can lose them with no problem, if you want to wait for an answer that solves your problem).

  • @ropbla9 Let’s try to make it work on Node.js. What error is occurring on Node.js, so this solution doesn’t work?

  • @ropbla9 I checked what was wrong with Node.js, correct and edit the answer, follow up on the response edition.

Browser other questions tagged

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