/**
* Archives content of HTML documents for dry-run scenarios with default values.
*
* @param {string} htmlString The HTML content to archive.
* @param {object} defaults An object containing default values for variables in the HTML.
* @returns {object} An object containing the archived content with default values applied.
*/
function archiveHtml(htmlString, defaults) {
// Create a temporary DOM element to parse the HTML string.
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
// Function to replace placeholders with default values.
function replacePlaceholders(node) {
if (node.nodeType === Node.TEXT_NODE) {
// Check for placeholders like {{variableName}}
const regex = /\{\{\s*([a-zA-Z0-9_-]+)\s*\}\}/g;
node.textContent = node.textContent.replace(regex, (match, variableName) => {
// Get the default value for the variable.
const defaultValue = defaults[variableName] || ''; // Default to empty string if not found.
return defaultValue;
});
} else if (node.nodeType === Node.ELEMENT_NODE) {
// Recursively process child nodes.
for (let i = 0; i < node.childNodes.length; i++) {
replacePlaceholders(node.childNodes[i]);
}
}
}
// Apply default values to the HTML content.
replacePlaceholders(doc.body);
// Extract the archived content as a string.
const archivedContent = doc.body.innerHTML;
return {
archivedContent: archivedContent,
};
}
Add your comment