代码之家  ›  专栏  ›  技术社区  ›  j_d

如何在循环中创建正则表达式?[副本]

  •  -1
  • j_d  · 技术社区  · 7 年前

    我目前有一个正则表达式,看起来像:

    const ignoreRegex = new RegExp(/^\/(?!fonts|static).*$/)

    但是,我还有一个动态字符串数组,如 "test" 这也需要被忽略。我需要以某种方式映射这个数组,并将每个字符串添加到正则表达式中,以便:

      const ignoreRegex = new RegExp(/^\/(?!fonts|static + ignoreRoutes.map(x => `|${x}`) + ).*$/)
    

    我该怎么做?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Vivek    7 年前

    你可以省略这个词 / / 围绕正则表达式并在RegExp构造函数中使用字符串。

    请参阅下面的代码。

    const ignoreFolders = ["fonts", "static"];
    const ignoreRoutes = ["route1", "route2"];
    const ignore = ignoreFolders.concat(ignoreRoutes);
    
    const ignoreRegex = new RegExp(`^\/(?!${ignore.join("|")}).*$`);
    
    console.log(ignoreRegex);

    如果字符串中有任何正则表达式特殊字符,它们将自动转义。

        2
  •  0
  •   Tiago Peres damanpreet singh    7 年前
    const ignoreRoutes = ["fonts","static","aaa","bbb","ccc"];
    const ignoreRegex = new RegExp(`^\\/(?!${ignoreRoutes.join("|")}).*$`);