@bnidev/js-utils
    Preparing search index...

    Function sanitizeHtml

    • Sanitizes a string of HTML, preserving only safe tags and attributes for rich text rendering.

      This function removes any tags and attributes that are not explicitly allowed, helping to prevent XSS (cross-site scripting) attacks and unwanted formatting. It is designed primarily for use with rich text editors, comments, or other user-generated content where a limited set of semantic HTML is acceptable.

      By default, only common formatting tags (<p>, <strong>, <ul>, etc.) are preserved. Layout and styling tags like <div> and <span> are excluded by design to keep the output clean and focused.

      Parameters

      • dirtyHtml: string

        The input HTML string to sanitize.

      • allowedTags: string[] = ...

        An array of tag names (lowercase) to allow. Defaults to safe formatting tags.

      • allowedAttributes: Record<string, string[]> = ...

        A map of tag names to allowed attributes. Keys and attribute names should be lowercase.

      Returns string

      The sanitized HTML string.

      This function uses the DOM API and is safe to run in the browser. It prevents XSS by stripping dangerous tags and attribute values.

      // ES Module
      import { sanitizeHtml } from '@bnidev/js-utils'

      // CommonJS
      const { sanitizeHtml } = require('@bnidev/js-utils')
      sanitizeHtml('<p onclick="alert()">Hi <strong>there</strong></p>')
      // → '<p>Hi <strong>there</strong></p>'