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

Node.js /g属性与nodejs中的变量组合,node.js,npm,Node.js,Npm,我尝试使用重命名一些文件 这是我的密码 //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

我尝试使用重命名一些文件

这是我的密码

//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'
,但不起作用。我只想使用一个变量重命名为
/g
(全局)属性,以替换所有出现的情况,而不仅仅是第一个实例


非常感谢您的帮助。

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

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

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

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