【问题标题】:Is there a way to add a variable to Regex and use them in JavaScript or TypeScript? [duplicate]有没有办法将变量添加到 Regex 并在 JavaScript 或 TypeScript 中使用它们? [复制]
【发布时间】:2019-09-18 23:18:52
【问题描述】:

我正在尝试使用类似于

的东西
/^(.*?)\.txt/

但我不想使用 .txt,而是想用变量替换它

【问题讨论】:

    标签: javascript regex typescript


    【解决方案1】:

    是的,您可以使用 RegExp 构造函数。

    var extension = ".txt";
    var reg = new RegExp("^(.*?)\\" + extension);
    
    console.log(reg);
    console.log(reg.test("test.txt"));
    console.log(reg.test("test.pdf"));

    【讨论】:

      【解决方案2】:

      你可以使用:

      function extMatch(ext){
          return new RegExp('^(.*?)\\.'+ext+'$');
      }
      /*  Even shorter, but messing with base prototypes is frowned upon.
          Use at your leisure. */
      String.prototype.extMatch=function(ext){
          let match=this.match(extMatch(ext));
          return match && match[1];
      }
      let str='foobar.css';
      let ext='css';
      console.log(str.match(extMatch(ext))[1]);
      console.log(str.extMatch(ext));
      
      console.log(str.extMatch('zip'));       // null if no match

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 2017-10-10
        相关资源
        最近更新 更多