简体   繁体   English

ReplaceAll 不替换所有递归 function

[英]ReplaceAll not replacing all in recursive function

I'm using a recursive function that takes a template string like this:我正在使用递归的 function,它采用如下模板字符串:

<div class='${classes}'>

and replaces the template literal placeholder ${classes} with valued from an object that looks like this:并将模板文字占位符 ${classes} 替换为 object 中的值,如下所示:

{ classes: 'bg-${color} text-${color}', color: 'blue' }

Something to note here is that within the object, there is more template string nesting, hence the reason for the recursive function.这里需要注意的是,在object内部,模板串嵌套比较多,所以才递归function。

The thing I cannot work out is why the replace all function is only replacing the 1st instance of ${color}, and leaving the second undefined.我无法解决的问题是为什么替换所有 function 只替换 ${color} 的第一个实例,而第二个实例未定义。

Working snippet below:下面的工作片段:

 function buildTemplate(string) { var matched = false; string = string.replaceAll(/\$\{(.*?)\}/g, function (match, key) { if (match) { matched = true; } const selection = selectors[key]; delete selectors[key]; return selection; }); if (matched) { string = buildTemplate(string); } console.log(string); } let templateString = "<div class='${classes}'>"; const selectors = { classes: 'bg-${color} text-${color}', color: 'blue' } buildTemplate(templateString);

You are deleting selectors , when you need it twice.当您需要两次时,您正在删除selectors
Remove line;删除线;

// delete selectors[key]

or selection get assigned nothingselection什么也没分配

No need to delete anything when it's an object that is accessed through a key.当它是通过密钥访问的 object 时,无需删除任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM