I'm using a recursive function that takes a template string like this:
<div class='${classes}'>
and replaces the template literal placeholder ${classes} with valued from an object that looks like this:
{ 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.
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.
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.
Remove line;
// delete selectors[key]
or selection
get assigned nothing
No need to delete anything when it's an object that is accessed through a key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.