Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何仅在目标对象中存在替换项时替换字符串?_Javascript_Regex_Expression - Fatal编程技术网

Javascript 如何仅在目标对象中存在替换项时替换字符串?

Javascript 如何仅在目标对象中存在替换项时替换字符串?,javascript,regex,expression,Javascript,Regex,Expression,我有下面的代码片段,这段代码将字符串中的令牌$ENV[accountsDomain]替换为itemobjectaccountsDomain:'www.yahoo.com',类似地用于accountsUrl 如何有条件地运行replace,仅当item[g1]存在时才替换字符串,因为这些键是可选的 const项={ accountsUrl:“www.google.com”, 帐户域:“www.yahoo.com” } const regex=/\$ENV\[(\w+)]/ 设s=“foo$ENV

我有下面的代码片段,这段代码将字符串中的令牌
$ENV[accountsDomain]
替换为
item
object
accountsDomain:'www.yahoo.com'
,类似地用于
accountsUrl

如何有条件地运行replace,仅当
item[g1]
存在时才替换字符串,因为这些键是可选的

const项={
accountsUrl:“www.google.com”,
帐户域:“www.yahoo.com”
}
const regex=/\$ENV\[(\w+)]/
设s=“foo$ENV[accountsDomain]bar”;
s=s.replace(正则表达式,(m,g1)=>项[g1]| | m);

控制台日志您不能在“替换”中执行此操作,必须在外部执行

试试这个:

const项={
accountsUrl:“www.google.com”,
帐户域:“www.yahoo.com”
}
函数替换项(项,键){
const regex=/\$ENV\[(\w+)]/
设s=`foo$ENV[${key}]bar`;
let[,match]=s.match(regex);
返回项[匹配]和&s.replace(正则表达式,(m,g1)=>项[g1]);
}
log('result with existing key:',replaceItem(item,'accountsDomain'))

console.log('result with un existing key:',replaceItem(item,'accDomain'))
如果
item[g1]
未定义,则返回匹配项。这不是预期的行为吗?