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