Find and replace bad words and obscenities with React
Stefan Skorpen
1 min read
If you allow your users to create content in your webapp, or if you make your own comment component, you would want to moderate the text that the user types in.
In my side project I want the users to create products with descriptions, as well as usernames and slugs for urls. I check all of these for profanities or swear words as best as I can.
I found this handy library called “obscenity”, and it already has a large library of forbidden words. This is perfect for this use case and this way I dont have to come up with all the bad words myself!
import {
RegExpMatcher,
TextCensor,
englishDataset,
englishRecommendedTransformers,
} from 'obscenity'
function badWordsDetector(input: string) {
// the input example is: 'fuck you little bitch'
const matcher = new RegExpMatcher({
...englishDataset.build(),
...englishRecommendedTransformers,
});
const censor = new TextCensor();
const matches = matcher.getAllMatches(input);
return censor.applyTo(input, matches);
// the censored text then returns: '%@$% you little **%@%'
}
0
Subscribe to my newsletter
Read articles from Stefan Skorpen directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by