2017-01-30 21:39:45 -05:00
|
|
|
function escapeRegexp(text) {
|
2017-01-30 21:45:04 -05:00
|
|
|
return text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
|
2017-01-30 21:39:45 -05:00
|
|
|
}
|
|
|
|
|
2016-11-08 16:36:34 -05:00
|
|
|
export function censor(text, censoredWords, censoredPattern) {
|
|
|
|
let patterns = [],
|
|
|
|
originalText = text;
|
|
|
|
|
2016-06-14 14:31:51 -04:00
|
|
|
if (censoredWords && censoredWords.length) {
|
2017-01-30 21:39:45 -05:00
|
|
|
patterns = censoredWords.split("|").map(t => `(${escapeRegexp(t)})`);
|
2016-11-08 16:36:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if (censoredPattern && censoredPattern.length > 0) {
|
2016-11-08 17:59:51 -05:00
|
|
|
patterns.push("(" + censoredPattern + ")");
|
2016-11-08 16:36:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if (patterns.length) {
|
2016-06-14 14:31:51 -04:00
|
|
|
let censorRegexp;
|
|
|
|
|
2016-11-08 16:36:34 -05:00
|
|
|
try {
|
|
|
|
censorRegexp = new RegExp("(\\b(?:" + patterns.join("|") + ")\\b)(?![^\\(]*\\))", "ig");
|
|
|
|
|
|
|
|
if (censorRegexp) {
|
|
|
|
let m = censorRegexp.exec(text);
|
|
|
|
|
|
|
|
while (m && m[0]) {
|
|
|
|
if (m[0].length > originalText.length) { return originalText; } // regex is dangerous
|
|
|
|
const replacement = new Array(m[0].length+1).join('■');
|
2017-01-30 21:39:45 -05:00
|
|
|
text = text.replace(new RegExp(`(\\b${escapeRegexp(m[0])}\\b)(?![^\\(]*\\))`, "ig"), replacement);
|
2016-11-08 16:36:34 -05:00
|
|
|
m = censorRegexp.exec(text);
|
|
|
|
}
|
2016-06-14 14:31:51 -04:00
|
|
|
}
|
2016-11-08 16:36:34 -05:00
|
|
|
} catch(e) {
|
|
|
|
return originalText;
|
2016-06-14 14:31:51 -04:00
|
|
|
}
|
|
|
|
}
|
2016-11-08 16:36:34 -05:00
|
|
|
|
2016-06-14 14:31:51 -04:00
|
|
|
return text;
|
|
|
|
}
|