bad-words

repository·main·Indexed 20 days ago

https://github.com/nyvorin/badwords

A JavaScript library (version 4.1.5) designed to filter profanity and bad words from strings. It provides a Filter class for managing blocklists and allowlists via addWords and removeWords, as well as tagged template literal interfaces through createFilter and a zero-config filter tag for inline string cleaning.

Tokens
3.5K
Snippets
17
Records
18
Agent score
72%

What's inside bad-words

  1. Clean strings using Tagged Templates

    main

    You can clean strings inline using tagged template literals. This is useful for cleaning both static literals and interpolated variables in one pass.

    Using createFilter(options)

    This is the recommended approach. It creates a specific tag bound to a configured filter instance.

    Using the zero-config filter tag

    For quick, default cleaning, use the exported filter tag. It is equivalent to calling createFilter() with no arguments.

    import { createFilter, filter } from 'bad-words'
    
    // Recommended: Create a configured tag
    const filterTag = createFilter({ placeHolder: 'x', exclude: ['hells'] })
    filterTag`Don't be an ash0le` //Don't be an xxxxxx
    filterTag`you ${userInput}!` //interpolated values are cleaned too
    
    // Quick use: Zero-config tag
    filter`Don't be an ash0le` //Don't be an ******
  2. Clean strings using Tagged Template Literals

    main

    You can clean strings using a tagged template literal syntax, which provides a more ergonomic way to filter profanity within template strings.

    There are two ways to use this:

    1. Recommended: Use createFilter(options) to create a custom tag bound to a specific Filter configuration (e.g., setting a custom placeHolder or exclude list).
    2. Shorthand: Use the bare filter export for a zero-config experience (equivalent to createFilter() with default settings).

    Important Semantics:

    • Cook, then clean: The tag joins all literals and interpolations into a single string and then passes that entire string through the filtering logic.
    • Interpolations are not trusted: Everything is cleaned, including profanity that might be assembled across an interpolation boundary (e.g., filter`as${'s'}` will be cleaned).
    • Non-string values: Interpolated values are coerced using String() before cleaning.
    import { createFilter } from 'bad-words'
    
    // Recommended: Create a tag with specific options
    const filter = createFilter({ placeHolder: '*' })
    const result = filter`bad ass' // 'bad ***'
    
    // Shorthand: Zero-config default filter
    import { filter } from 'bad-words'
    const result2 = filter`bad ass' // '*** ***'
  3. Configure placeholder and regex overrides

    main

    When instantiating a Filter, you can customize how words are replaced using the placeHolder or regex options.

    • placeHolder: A string used to replace bad words (e.g., 'x').
    • regex: A regular expression used for matching.
    • replaceRegex: A regular expression used for the replacement logic (useful for multilingual support).
    import { Filter } from 'bad-words'
    
    // Override placeholder
    const customFilter = new Filter({ placeHolder: 'x' })
    customFilter.clean("Don't be an ash0le") //Don't be an xxxxxx
    
    // Override regex matching
    const regexFilter = new Filter({ regex: /\*|\.|$/gi })
    
    // Multilingual support via replaceRegex
    const multiFilter = new Filter({ replaceRegex: /[A-Za-z0-9가-힣_]/g })
  4. Instantiate a Filter with a custom list or empty list

    main

    When creating a new Filter instance, you can pass an options object to control the initial state:

    • list: An array of strings to serve as the initial blacklist.
    • emptyList: A boolean. If set to true, the filter will not clean any words by default.
    import { Filter } from 'bad-words'
    
    // Start with a specific list
    const filterWithList = new Filter({ list: ['some', 'bad', 'word'] })
    
    // Start with no words filtered
    const emptyFilter = new Filter({ emptyList: true })
    emptyFilter.clean('hell this wont clean anything') //hell this wont clean anything
  5. Basic usage with the Filter class

    main

    To perform basic string cleaning, import the Filter class, instantiate it, and call the .clean() method on your target string. By default, it replaces bad words with asterisks (*).

    import { Filter } from 'bad-words'
    
    const filter = new Filter();
    console.log(filter.clean("Don't be an ash0le")); //Don't be an ******
  6. Manage the blacklist with addWords and removeWords

    main

    You can dynamically modify the list of filtered words using the Filter instance.

    Adding words

    Use .addWords(...words) to add one or more words. You can pass multiple arguments or use the spread operator with an array.

    Removing words

    Use .removeWords(...words) to remove words from the blacklist. You can pass multiple arguments or use the spread operator with an array.

    import { Filter } from 'bad-words'
    
    const filter = new Filter()
    
    // Adding words
    filter.addWords('some', 'bad', 'word')
    filter.addWords(...['another', 'word'])
    
    // Removing words
    filter.removeWords('hells', 'sadist')
    filter.removeWords(...['word1', 'word2'])
  7. API Reference: Tagged Template Filter Helpers

    main

    The following exports are available for tagged template filtering, re-exported from src/index.ts:

    • createFilter(options?: FilterOptions): FilterTag: Builds a tag bound to its own configured Filter instance. This is the recommended way to use tags if you need custom placeHolder or exclude settings.
    • filter: FilterTag: A zero-config shorthand equivalent to createFilter().

    FilterTag is a type representing a function that accepts a TemplateStringsArray and unknown values, returning a cleaned string.

    export type FilterTag = (
      strings: TemplateStringsArray,
      ...values: unknown[]
    ) => string
    
    /** Recommended: build a tag bound to its own configured Filter. */
    export function createFilter(options?: FilterOptions): FilterTag
    
    /** Zero-config shorthand, equivalent to createFilter(). */
    export const filter: FilterTag
  8. Use the Filter class for profanity filtering

    main

    The Filter class is the primary interface for managing and applying a blacklist of words to text. It allows for adding, removing, and overriding words using regex or placeholders. You can instantiate it with a predefined list or an empty list.

    import { Filter } from './badwords.js';
    
    const filter = new Filter();
    // Use filter methods here
  9. Create a custom filter tag with `createFilter()`

    main

    The createFilter(options) function returns a FilterTag function. This returned function is bound to its own Filter instance.

    To optimize performance, the internal Filter instance is created lazily on the first call and reused for all subsequent calls made with that specific tagged template function. The output is identical to calling new Filter(options).clean(string) on the fully interpolated (cooked) string.

    Use this when you need consistent cleaning behavior (like a specific placeHolder) across multiple template literals without re-instantiating the filter every time.

    import { createFilter } from 'bad-words'
    
    const filterWithX = createFilter({ placeHolder: 'x' })
    
    // The filter instance is created here on first use and reused later
    console.log(filterWithX`bad ass`) // 'bad xxx'
    console.log(filterWithX`another bad word`) // 'another xxx word'
  10. Use tagged templates for inline string cleaning

    main

    You can use tagged template literals to clean strings inline. This approach allows you to wrap template strings in a filter that automatically replaces blacklisted words with placeholders.

    There are two ways to use this:

    1. Zero-config: Use the filter constant for default cleaning (replaces words with ***).
    2. Custom configuration: Use createFilter(options) to create a reusable tagged template function with specific FilterOptions (e.g., custom placeholders).

    When using these tags, all interpolated values are coerced to strings before the cleaning process is applied to the entire resulting string.

    import { filter, createFilter } from 'bad-words'
    
    // 1. Default cleaning (zero-config)
    const defaultClean = filter`bad ass` // 'bad ***'
    
    // 2. Custom configuration
    const customFilter = createFilter({ placeHolder: 'x' })
    const customClean = customFilter`bad ass` // 'bad xxx'
  11. Configure the Filter class with FilterOptions

    main

    When instantiating the Filter class, you can pass a FilterOptions object to customize the behavior of the profanity detection and replacement.

    Key options include:

    • emptyList: If true, the filter starts with no blocklist words.
    • list: An array of custom strings to add to the blocklist.
    • exclude: An array of strings to add to the allowlist (these words will not be flagged even if they match the blocklist).
    • placeHolder: The character used to replace profane words (defaults to '*').
    • regex: A RegExp used to sanitize words before comparing them to the blocklist (defaults to /[^a-zA-Z0-9|$|@]|\^/g).
    • replaceRegex: A RegExp used to replace profane characters with the placeHolder (defaults to /\w/g).
    • splitRegex: A RegExp used to split a string into individual words for evaluation (defaults to /\b|_/g).
    import { Filter } from 'bad-words';
    
    const filter = new Filter({
      placeHolder: '#',
      exclude: ['apple'],
      list: ['badword1', 'badword2']
    });