Function sanitizeTextForRender

  • Sanitizes text for safe HTML rendering by escaping potentially dangerous characters while preserving valid HTML tags.

    This function performs the following transformations:

    • Converts newline characters (\n) to HTML line breaks (
      )
    • Escapes stray '<' characters that are not part of valid HTML tags (e.g., "x < 5" → "x < 5")
    • Escapes stray '>' characters that are not part of valid HTML tags (e.g., "x > 5" → "x > 5")
    • Preserves valid HTML tags and their attributes (e.g.,
      , ,

      )

    LIMITATIONS: This regex-based approach has known limitations:

    • Cannot properly handle '>' characters inside HTML attributes (e.g.,
      may not work correctly)
    • Complex nested quotes or edge cases may not be handled perfectly
    • For more complex HTML sanitization needs, consider using a proper HTML parser

    Returns

    The sanitized text safe for HTML rendering, or the original value if null/undefined.

    Example

    sanitizeTextForRender('Hello\nWorld') // 'Hello<br>World'
    sanitizeTextForRender('if x < 5') // 'if x &lt; 5'
    sanitizeTextForRender('<div>Hello</div>') // '<div>Hello</div>'
    sanitizeTextForRender('Price < $100 <strong>Sale!</strong>') // 'Price &lt; $100 <strong>Sale!</strong>'

    Parameters

    • text: undefined | null | string

      The text to sanitize. Can be null or undefined.

    Returns string

Generated using TypeDoc