UNPKG

@contentstack/utils

Version:
22 lines 1.61 kB
export function sanitizeHTML(input, allowedTags, allowedAttributes) { if (allowedTags === void 0) { allowedTags = ['p', 'a', 'strong', 'em', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'sub', 'u', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'span', 'fragment', 'sup', 'strike', 'br', 'img', 'colgroup', 'col', 'div']; } if (allowedAttributes === void 0) { allowedAttributes = ['href', 'title', 'target', 'alt', 'src', 'class', 'id', 'style', 'colspan', 'rowspan', 'content-type-uid', 'data-sys-asset-uid', 'sys-style-type', 'data-type', 'data-width', 'data-rows', 'data-cols', 'data-mtec']; } // Replace newline characters with <br /> before processing the HTML tags input = input.replace(/\n/g, '<br />'); // Regular expression to find and remove all HTML tags except the allowed ones var sanitized = input.replace(/<\/?([a-z][a-z0-9]*)\b[^<>]*>/gi, function (match, tag) { return allowedTags.includes(tag.toLowerCase()) ? match : ''; }); // Regular expression to remove all attributes except the allowed ones var cleaned = sanitized.replace(/<([a-z][a-z0-9]*)\b[^<>]*>/gi, function (match, tag) { if (!allowedTags.includes(tag.toLowerCase())) { return match; // Ignore tags not in allowedTags } // For each tag that is allowed, clean its attributes return match.replace(/\s([a-z\-]+)=['"][^'"]*['"]/gi, function (attributeMatch, attribute) { return allowedAttributes.includes(attribute.toLowerCase()) ? attributeMatch : ''; }); }); return cleaned; } //# sourceMappingURL=sanitize.js.map