Word Filter

4

How can I make a Javascript word filter? For example, I have a div and within that div I do not want to have certain words that are inside an array:

var badWords = ['teste', 'teste1', 'oteste2'];

How do I check if these words exist in the text and replace their content so that the first letter of that word appears, but the rest is marked with asterisks?

For example:

<div>Este texto tem as palavras: teste, teste1 e oteste2, e eu quero filtrar as palavras teste, oteste1 e teste2</div>

The content above would be replaced by something like this:

<div>Este texto tem as palavras: t****, t***** e o******, e eu quero filtrar as palavras t****, t***** e o******</div>

Remembering that I can not use jQuery, I would need to be in Javascript purely because it does not justify using the entire library just to do this ...

    
asked by anonymous 09.07.2014 / 19:35

2 answers

5

You can use RegExp:

var arr = ['teste', 'teste1', 'oteste2'];
var f = document.querySelector('div').textContent;

arr.forEach(function(el, index, arr) {
    var regexp = new RegExp("\b(" + el + ")\b", "g");
    f = f.replace(regexp, el.substr(0,1) + el.substring(1).replace(/./g, "*"));
});

document.querySelector('div').textContent = f;

Fiddle

    
09.07.2014 / 20:16
6

I'll let you turn to div and change the innerHtml or innerText property of it, since you do not want to use jQuery.

For the rest:

var badWords = { // Isso vai ser nosso dicionário.
    "teste": "t****",
    "teste1": "t*****",
    "oteste2": "o******",
    "Supercaligrafilistiespialidocio": "S******************************"
    /* etc, etc...*/
}

function changeWords (input) {
    var text = input.split(" "); // Isso pega a string de input e quebra em palavras separadas por espaços;
    for (var i = 0; i < text.length; i++) {
        var word = text[i];
        if (badWords[word]) { // Essa é a sintaxe pra ver se algo está no dicionário
            text[i] = badWords[word];
        }
    }
    return text.join(" "); // Isso junta todas as palavras num texto de novo, separadas por espaços.
}
    
09.07.2014 / 20:01