# Censored pattern

**URL:** <https://meta.discourse.org/t/censored-pattern/66912>\
**Category:** Bug\
**Created:** [July 27, 2017, 9:40am UTC](https://meta.discourse.org/t/censored-pattern/66912 "2017-07-27T09:40:35Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![Stranik](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/stranik/32/85638_2.png) [@Stranik](https://meta.discourse.org/u/Stranik)\
**Post date:** [September 29, 2017, 8:50am UTC](https://meta.discourse.org/t/censored-pattern/66912/8 "2017-09-29T08:50:17Z")

</div>

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 || "&#9632;";
> 
> 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);
> }
> 
> ```

---

_[View the full topic](https://meta.discourse.org/t/censored-pattern/66912)._
