striptags

repository·main·Indexed 19 days ago

https://github.com/ericnorris/striptags

A TypeScript implementation of PHP's strip_tags function designed to remove HTML tags from strings. It provides a striptags() function for basic stripping and a StateMachine class for processing streaming text. The library focuses on preventing XSS by default and allows customization via StateMachineOptions, including allowedTags, disallowedTags, tagReplacementText, and encodePlaintextTagDelimiters.

Tokens
1.8K
Snippets
8
Records
9
Agent score
66%

What's inside striptags

  1. Understand XSS safety in striptags

    main

    By default, striptags is safe to use as text within an HTML tag because it removes all potential XSS vectors.

    Warning: This safety guarantee is removed if you specify either allowedTags or disallowedTags. A malicious user can still achieve XSS via attributes in an allowed tag, such as <img onload="alert(1);">.

    Additionally, striptags automatically HTML encodes < and > characters followed by whitespace to prevent them from being interpreted as tags by browsers. You can disable this via encodePlaintextTagDelimiters: false if the output is intended for plaintext-only environments.

  2. Understand TagMode

    main

    The TagMode enum defines the two primary modes for handling tags within the state machine:

    • TagMode.Allowed: The tag is recognized as part of the permitted set and will be preserved in the output.
    • TagMode.Disallowed: The tag is recognized as a tag but is not permitted, triggering the use of tagReplacementText and stripping the tag's contents/attributes.
    export const enum TagMode {
        Allowed,
        Disallowed,
    }
  3. Use the StateMachine class for streaming text

    main

    If you are processing a stream of text where a tag might be split across multiple chunks (e.g., <a in one chunk and href="..." in another), use the StateMachine class. It persists state across multiple calls to .consume(), ensuring that partial tags are handled correctly.

    // commonjs
    const StateMachine = require("striptags").StateMachine;
    
    // alternatively, as an es6 import
    // import { StateMachine } from "striptags";
    
    const instance = new StateMachine();
    
    console.log(instance.consume("some text with <a") + instance.consume("tag>and more text"));
    // Output: "some text with and more text"
  4. Use the striptags function for basic tag stripping

    main

    The striptags function removes HTML tags from a string. By default, it removes all tags and prevents XSS. You can pass an optional StateMachineOptions object to customize behavior, such as allowing specific tags or providing replacement text for stripped tags.

    // commonjs
    const striptags = require("striptags").striptags;
    
    // alternatively, as an es6 import
    // import { striptags } from "striptags";
    
    var html = `<a href="https://example.com">lorem ipsum <strong>dolor</strong> <em>sit</em> amet</em>`.trim();
    
    console.log(striptags(html)); // Removes all tags
    console.log(striptags(html, { allowedTags: new Set(["strong"]) })); // Allows <strong>
    console.log(striptags(html, { tagReplacementText: "🍩" })); // Replaces tags with emoji
  5. Configure StateMachineOptions

    main

    The StateMachineOptions interface is used to define how the tag stripping state machine behaves, specifically regarding which tags are permitted and how delimiters are handled.

    • allowedTags (optional): A Set<string> of tag names that are permitted. If provided, only these tags will be kept.
    • disallowedTags (optional): A Set<string> of tag names that are explicitly forbidden. If provided, these tags will be stripped.
    • tagReplacementText (required): The string used to replace a tag when it is disallowed.
    • encodePlaintextTagDelimiters (required): A boolean determining whether < and > characters found in plaintext (outside of actual tags) should be encoded as &lt; and &gt;.
    export interface StateMachineOptions {
        readonly allowedTags?: Set<string>;
        readonly disallowedTags?: Set<string>;
        readonly tagReplacementText: string;
        readonly encodePlaintextTagDelimiters: boolean;
    }
  6. Configure striptags via StateMachineOptions

    main

    You can customize the stripping behavior using the following options in the options argument of striptags() or the StateMachine constructor:

    • allowedTags: A Set<string> of tag names to allow. Takes precedence over disallowedTags. (Default: undefined)
    • disallowedTags: A Set<string> of tag names to remove. Ignored if allowedTags is set. (Default: undefined)
    • tagReplacementText: A string used to replace tags that are stripped. (Default: "")
    • encodePlaintextTagDelimiters: A boolean that, when true, HTML encodes < and > characters followed by whitespace. (Default: true)
    // Example configuration
    striptags(html, {
      allowedTags: new Set(["b", "i"]),
      tagReplacementText: " [tag] `,
      encodePlaintextTagDelimiters: false
    });
  7. Use the StateMachine class for manual text consumption

    main

    For scenarios where you need to process text character-by-character or maintain state across multiple chunks of text, you can instantiate the StateMachine class directly.

    Use the .consume(text: string): string method to feed text into the machine. The machine maintains its internal state (e.g., whether it is currently inside a tag or in plaintext) between calls.

    import { StateMachine } from 'striptags';
    
    const machine = new StateMachine({ tagReplacementText: "[TAG]" });
    
    const part1 = machine.consume("<div>Hello");
    const part2 = machine.consume("World</div>");
    
    console.log(part1 + part2); // "[TAG]HelloWorld[TAG]"
  8. Use the striptags() function to strip HTML tags

    main

    The striptags() function is the primary entrypoint for removing HTML tags from a string. It accepts the input text and an optional Partial<StateMachineOptions> object to customize behavior. It returns the processed string with tags removed.

    import striptags from 'striptags';
    
    const input = "<p>Hello <b>World</b>!</p>";
    const output = striptags(input);
    // output: "Hello World!"