npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

badword-validator

v1.0.3

Published

A flexible TypeScript/JavaScript library for detecting and sanitizing inappropriate language with customizable word lists and plugins

Downloads

290

Readme

BadWord Validator

npm version License: MIT TypeScript

A flexible TypeScript/JavaScript library designed to help developers identify and sanitize inappropriate or offensive language in user-generated content. Built with modern ES modules, full TypeScript support, and an extensible plugin architecture.

✨ Features

  • 🔷 Dual Language Support: Written in TypeScript with full type definitions, works seamlessly in both TS and JS projects
  • 📝 Customizable Word Lists: Define your own lists of bad words categorized by severity levels (low, medium, high, highest)
  • 🔌 Plugin System: Extend functionality with plugins for additional features like XSS protection
  • 🛡️ Sanitization & Validation: Easily sanitize and validate text input to ensure it meets your content guidelines
  • Modern ES Modules: ES2022 format with full tree-shaking support for optimal bundle sizes
  • 🎯 Zero Dependencies: Lightweight library with no external dependencies
  • 🧪 Tested: Test suite with unit test-case
  • 📦 Ready for Production: Battle-tested patterns and enterprise-ready architecture

📥 Installation

npm install badword-validator
yarn add badword-validator
pnpm add badword-validator

Usage

JavaScript

import { BadWordFilter } from 'badword-validator';

const filter = new BadWordFilter();
const result = filter.sanitize("What the hell is going on?");
console.log(result); // "What the **** is going on?"

TypeScript

import { BadWordFilter, ValidatorResult } from 'badword-validator';

const filter: BadWordFilter = new BadWordFilter();
const result: ValidatorResult = filter.validate("Some text here");
console.log(result); // { found: ['word'], level: 'medium' }

BadWordFilter Class

The main class for filtering and validating text content.

Constructor

const filter = new BadWordFilter();

Methods

sanitize(text: string): string

Sanitizes the input text by replacing bad words with asterisks.

const clean = filter.sanitize("This is damn good!");
// Returns: "This is **** good!"
validate(text: string): ValidatorResult

Validates text and returns information about found bad words.

const result = filter.validate("Some bad text");
// Returns: { found: string[], level: 'low' | 'medium' | 'high' | 'highest' | null }
use(plugin: Plugin): void

Adds a plugin to extend functionality.

filter.use({ 
  name: "CustomPlugin", 
  words: { medium: ["word1", "word2"] } 
});

Plugin Interface

interface Plugin {
  name: string;
  words?: WordList;
  sanitize?(text: string): string;
  validate?(text: string): ValidatorResult;
}

Word List Structure

interface WordList {
  low?: string[];      // Mild inappropriate words
  medium?: string[];   // Moderately inappropriate words  
  high?: string[];     // Highly inappropriate words
  highest?: string[];  // Extremely inappropriate words
}

🔧 Advanced Usage

TypeScript Usage

⚙️ Basic Example with Types

import { BadWordFilter, Plugin, ValidatorResult, WordList } from "badword-validator";

const filter: BadWordFilter = new BadWordFilter();
const text: string = "What the hell are you doing?";
const cleanText: string = filter.sanitize(text);
console.log(cleanText); // Output: What the **** are you doing?

// Fully typed validation result
const result: ValidatorResult = filter.validate(text);
console.log(result); // { found: ['hell'], level: 'medium' }

🔧 Custom Typed Plugin

import { BadWordFilter, Plugin, WordList } from "badword-validator";

interface CustomPlugin extends Plugin {
  customMethod?: () => void;
}

const customWordList: WordList = {
  low: ['darn'],
  medium: ['damn', 'hell'],
  high: ['shit']
};

const customPlugin: CustomPlugin = {
  name: "TypedCustomPlugin",
  words: customWordList,
  validate(text: string) {
    // Custom validation logic with full type safety
    const words = text.toLowerCase().split(' ');
    const found: string[] = [];
    let level: keyof WordList | null = null;
    
    // Implementation details...
    return { found, level };
  },
  customMethod() {
    console.log('Custom method executed!');
  }
};

const filter = new BadWordFilter();
filter.use(customPlugin);

⚒️ Advanced Usage

Custom Word Lists

import { BadWordFilter } from 'badword-validator';

const filter = new BadWordFilter();

// Add custom words with different severity levels
filter.use({
  name: 'CustomWordList',
  words: {
    low: ['darn', 'crap'],
    medium: ['damn', 'hell'], 
    high: ['shit', 'ass'],
    highest: ['fuck', 'bitch']
  }
});

const text = "This is some damn shit!";
console.log(filter.validate(text));
// { found: ['damn', 'shit'], level: 'high' }

XSS Protection Plugin

import { BadWordFilter } from 'badword-validator';
import { xssProtection } from 'badword-validator/plugins/xssProtection';

const filter = new BadWordFilter();
filter.use(xssProtection);

const maliciousInput = '<script>alert("XSS")</script>Hello world!';
const safe = filter.sanitize(maliciousInput);
console.log(safe); // "[removed-script]Hello world!"

Express.js Middleware

import { BadWordFilter } from 'badword-validator';

const filter = new BadWordFilter();

export function contentModerationMiddleware(req, res, next) {
  if (req.body) {
    // Sanitize string bodies
    if (typeof req.body === 'string') {
      req.body = filter.sanitize(req.body);
    }
    // Recursively sanitize object properties
    else if (typeof req.body === 'object') {
      req.body = sanitizeObject(req.body, filter);
    }
  }
  next();
}

function sanitizeObject(obj, filter) {
  const sanitized = { ...obj };
  for (const [key, value] of Object.entries(sanitized)) {
    if (typeof value === 'string') {
      sanitized[key] = filter.sanitize(value);
    } else if (typeof value === 'object' && value !== null) {
      sanitized[key] = sanitizeObject(value, filter);
    }
  }
  return sanitized;
}

Custom Validation Plugin

import { BadWordFilter, Plugin, ValidatorResult } from 'badword-validator';

const contextAwarePlugin: Plugin = {
  name: 'ContextAwareFilter',
  validate(text: string): ValidatorResult {
    // Custom logic for context-aware validation
    const suspiciousPatterns = [
      /\b\w*\d+\w*\b/g, // Words with numbers (potential spam)
      /(.)\1{3,}/g,     // Repeated characters (potential spam)
    ];
    
    const found: string[] = [];
    for (const pattern of suspiciousPatterns) {
      const matches = text.match(pattern);
      if (matches) found.push(...matches);
    }
    
    return {
      found,
      level: found.length > 0 ? 'medium' : null
    };
  },
  sanitize(text: string): string {
    return text
      .replace(/\b\w*\d+\w*\b/g, '[filtered]')
      .replace(/(.)\1{3,}/g, (match) => match[0].repeat(2));
  }
};

const filter = new BadWordFilter();
filter.use(contextAwarePlugin);

🌍 Environment Compatibility

| Environment | Support | Notes | |-------------|---------|-------| | Node.js | ✅ v18+ | Full ES module support | | TypeScript | ✅ v4+ | Complete type definitions | | Browser | ✅ Modern | ES2022+ required |

🧪 Testing

Run the test suite:

npm test

Run tests with coverage:

npm run test:coverage

🔧 Development

  1. Clone the repository:

    git clone https://github.com/illuminationZ/badword-validator.git
    cd badword-validator
  2. Install dependencies:

    npm install
  3. Build the project:

    npm run build
  4. Run tests:

    npm test
  5. Development mode (watch for changes):

    npm run dev

📝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Built with modern TypeScript and ES modules
  • Inspired by the need for flexible content moderation
  • Thanks to all contributors and users

📊 Package Stats

  • Zero dependencies - Lightweight and fast
  • Full TypeScript support - Complete type definitions
  • ES Module format - Tree-shaking friendly
  • Comprehensive tests - High coverage and reliability

Made with ❤️ for safer content experiences