Perhaps with the help of regular expressions it will not be possible to rewrite this. (
I tried it, but it’s a terrible option (the introduction of cycles.) It works, but this option is very bad.
Summary
function escapeRegexp(text) {
return text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}
export function censorFn(censoredWords, censoredPattern, replacementLetter) {
let patterns = [];
replacementLetter = replacementLetter || "■";
if (censoredWords && censoredWords.length) {
patterns = censoredWords.split("|").map(t => `(${escapeRegexp(t)})`);
}
if (censoredPattern && censoredPattern.length > 0) {
patterns.push("(" + censoredPattern + ")");
}
if (patterns.length) {
let censorRegexp;
try {
return function(text) {
let original = text;
let ind=0;
patterns.forEach(function(item, i, arr) {
item=item.replace(')','');
item=item.replace('(','');
original=maxsearch(original,item,ind);
});
return original;
};
} catch(e) {
// fall through
}
}
return function(t){ return t;};
}
export function maxsearch(original,item,ind){
let mas=original.split(' ');
ind=mas.indexOf(item);
if (ind>=0){
mas[ind]='…';
return maxsearch(mas.join(' '),item,ind);
}else{
return mas.join(' ');
}
}
export function censor(text, censoredWords, censoredPattern, replacementLetter) {
return censorFn(censoredWords, censoredPattern, replacementLetter)(text);
}