word-sensor is designed to be easy to use but flexible enough for more advanced use cases. Below are several usage examples ranging from basic to advanced scenarios.
Basic Usage
Filter a list of simple words from a text:
import { WordSensor } from 'word-sensor';
const sensor = new WordSensor(['foo', 'bar']);
const result = sensor.scan('This is a foo message with BAR content.');
console.log(result);
/*
{
hasMatch: true,
matchedWords: ['foo', 'bar'],
censoredText: 'This is a *** message with *** content.'
}
*/
Case Insensitive Matching
The matching is case-insensitive by default, so BAR, Bar, and bar are treated the same.
const sensor = new WordSensor(['badword']);
const result = sensor.scan('That was a BADWORD!');
console.log(result.matchedWords); // ['badword']
Custom Censor Character
You can pass a second parameter to change the censor character (default is *):
const sensor = new WordSensor(['secret'], { censorChar: '#' });
const result = sensor.scan('This is a secret message.');
console.log(result.censoredText); // This is a ###### message.
Disable Censoring (Detection Only)
If you only want to detect words but not replace them in the text:
const sensor = new WordSensor(['spoiler'], { censor: false }); const result = sensor.scan('Here comes a spoiler alert!'); console.log(result.hasMatch); // true console.log(result.censoredText); // original text remains unchanged
const sensor = new WordSensor(['spoiler'], { censor: false });
const result = sensor.scan('Here comes a spoiler alert!');
console.log(result.hasMatch); // true
console.log(result.censoredText); // original text remains unchanged
Matching Whole Words Only
You can enable whole-word matching to avoid partial matches (e.g., avoid matching ass in passenger):
const sensor = new WordSensor(['ass'], { wholeWords: true });
const result = sensor.scan('He is a passenger.');
console.log(result.hasMatch); // false
Using Regular Expressions
For more complex filtering logic, you can use custom patterns via RegExp:
const sensor = new WordSensor([/f[o0]{2}/i]); // Matches 'foo', 'f00', etc.
const result = sensor.scan('That was so f00lish!');
console.log(result.hasMatch); // true
console.log(result.matchedWords); // ['f00']
Note: When using RegExp, only literal matches (e.g., /badword/) will be listed in matchedWords, not the original input word.
Dynamically Updating Word List
You can dynamically add or update the list of words:
const sensor = new WordSensor(['bad']);
sensor.addWords(['ugly']);
sensor.removeWords(['bad']);
const result = sensor.scan('That was ugly and bad.');
console.log(result.matchedWords); // ['ugly']
Options
Here are the available options you can pass when creating a WordSensor instance:
Option | Type | Default | Description |
|---|---|---|---|
|
|
| Whether to replace matched words in the output |
|
|
| The character used for censoring |
|
|
| Only match complete words (uses word boundaries) |