1. /**
  2. * Archives content of HTML documents for dry-run scenarios with default values.
  3. *
  4. * @param {string} htmlString The HTML content to archive.
  5. * @param {object} defaults An object containing default values for variables in the HTML.
  6. * @returns {object} An object containing the archived content with default values applied.
  7. */
  8. function archiveHtml(htmlString, defaults) {
  9. // Create a temporary DOM element to parse the HTML string.
  10. const parser = new DOMParser();
  11. const doc = parser.parseFromString(htmlString, 'text/html');
  12. // Function to replace placeholders with default values.
  13. function replacePlaceholders(node) {
  14. if (node.nodeType === Node.TEXT_NODE) {
  15. // Check for placeholders like {{variableName}}
  16. const regex = /\{\{\s*([a-zA-Z0-9_-]+)\s*\}\}/g;
  17. node.textContent = node.textContent.replace(regex, (match, variableName) => {
  18. // Get the default value for the variable.
  19. const defaultValue = defaults[variableName] || ''; // Default to empty string if not found.
  20. return defaultValue;
  21. });
  22. } else if (node.nodeType === Node.ELEMENT_NODE) {
  23. // Recursively process child nodes.
  24. for (let i = 0; i < node.childNodes.length; i++) {
  25. replacePlaceholders(node.childNodes[i]);
  26. }
  27. }
  28. }
  29. // Apply default values to the HTML content.
  30. replacePlaceholders(doc.body);
  31. // Extract the archived content as a string.
  32. const archivedContent = doc.body.innerHTML;
  33. return {
  34. archivedContent: archivedContent,
  35. };
  36. }

Add your comment