import config from 'config'; import { TextCensor, RegExpMatcher, englishDataset, englishRecommendedTransformers, DataSet, pattern, // asteriskCensorStrategy, } from 'obscenity'; const textCensor = new TextCensor(); // built-in asterisk strategy replaces entire word textCensor.setStrategy(({ input, startIndex, endIndex, matchLength, }) => { if (matchLength <= 2) { return '*'.repeat(matchLength); } return `${input.at(startIndex)}${'*'.repeat(matchLength - 2)}${input.at(endIndex)}`; }); const dataset = new DataSet().addAll(englishDataset); config.restrictions.censors.forEach((word) => { dataset.addPhrase((phrase) => phrase .setMetadata({ originalWord: word }) .addPattern(pattern`${word}`)); }); const matcher = new RegExpMatcher({ ...dataset.build(), ...englishRecommendedTransformers, }); export function censor(text, restriction) { if (!text) { return null; } if (!restriction) { return text; } const censorMatches = matcher.getAllMatches(text); const censoredText = textCensor.applyTo(text, censorMatches); return censoredText; }