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

/g属性与nodejs中的变量组合

  •  0
  • Cody  · 技术社区  · 7 年前

    我尝试使用重命名一些文件 replace-in-file

    这是我的密码

    //variable
    const oldText = "some text"
    const newText = "new text"
    
    const replace = require("replace-in-file");
    const options = {
     files: "./filepath",
     from: oldText/g,
     to: newText
    };
    

    我的问题是如何使用我的 oldText 可变的 /g ?

    我试过这个 '/' + oldText + '/g' 但这是行不通的。我只想使用一个变量来重命名 (全局)属性以替换所有引用,而不仅仅是第一个实例。

    1 回复  |  直到 7 年前
        1
  •  2
  •   jfriend00    7 年前

    如果您试图使用变量的内容动态构造正则表达式,那么您将使用构造函数 new RegExp(str, opt) 您可以在其中传递字符串和选项:

    const options = {
     files: "./filepath",
     from: new RegExp(oldText, 'g'),
     to: newText
    };
    
    推荐文章