JavaScript:Replace部分文本存储在以'$&引用;?

JavaScript:Replace部分文本存储在以'$&引用;?,javascript,regex,replace,Javascript,Regex,Replace,我知道替换可以用其他最简单的方法来完成,但是由于代码的复杂性,我必须按照下面开始的方法来完成 我需要的是将$WORD.A和$WORD.B替换为TEST,但行中出现了问题 newValue.replace(new RegExp(potentialWord, 'g'), 'TEST'); 在下面的代码中,我的问题是当我想用另一个变量替换以字符$开头的字符串变量时 const段落='My text for replace this$WORD.A和this$WORD.B'; 让newValue=段落

我知道替换可以用其他最简单的方法来完成,但是由于代码的复杂性,我必须按照下面开始的方法来完成

我需要的是将
$WORD.A
$WORD.B
替换为
TEST
,但行中出现了问题

newValue.replace(new RegExp(potentialWord, 'g'), 'TEST');
在下面的代码中,我的问题是当我想用另一个变量替换以字符
$
开头的字符串变量时

const段落='My text for replace this$WORD.A和this$WORD.B';
让newValue=段落;
日志(“旧文本:”,段落);
常量正则表达式=/(?:\$)([A-Z]+(?:\[A-Z])*)/gm;
const foundposiblewords=newValue.match(regex);
console.log(foundablewords);
if(foundposiblewords!=null&&foundposiblewords!==未定义){
FoundableWords.forEach((潜在字)=>{
替换(新的RegExp(潜在字'g'),'TEST');
});
}
log(“新文本:”,newValue)您可以使用:

const段落='My text for replace this$WORD.A和this$WORD.B';
const res=段落。替换(/[\$][\w\.]+/g,“测试”);
控制台日志(res)您可以使用:

const段落='My text for replace this$WORD.A和this$WORD.B';
const res=段落。替换(/[\$][\w\.]+/g,“测试”);

控制台日志(res)这样的东西符合您的需要吗

const paragration='My text for replace this$WORD.A和this$WORD.B以及$other_WORD';
常数re=/\$[^\s]+/gm;
常量替换=‘测试’;
var结果=段落替换(re,替换);

日志(“新文本:”,结果)这样的东西符合您的需要吗

const paragration='My text for replace this$WORD.A和this$WORD.B以及$other_WORD';
常数re=/\$[^\s]+/gm;
常量替换=‘测试’;
var结果=段落替换(re,替换);
日志(“新文本:”,结果)