Word filter

Asked

Viewed 1,258 times

4

How can I make a Javascript word filter? For example, I have a div and within that div do not want there to be 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 gets 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 above content 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’t use jQuery, it would need to be in pure Javascript precisely because it doesn’t justify using the full library just to do this...

  • What you tried so far?

  • @Beet This is the problem I’m not experienced with Javascript, so everything I tried didn’t work. The most I could find was the index of these words, see: http://pastebin.com/5tvXRj1c All other tests failed... I tried. replace(), and others...

  • Dude, these texts are generated like? in what language? Come from a database? I would not use javascript for this, if disabled in the browser, it was already your filter.

  • The texts comes from a friendly common HTML page.. No databases.

  • But why write HTML words that will be filtered? It wouldn’t be easier not to write what you can’t?

2 answers

6

I’ll let you turn around and get the div and change property innerHtml or innerText from her, since you don’t want to use jQuery.

Otherwise:

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.
}
  • 1

    Marypoppinsmention++;

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.