See if any of the array value exists in a string?

1

I'm trying to make a language filter where it checks after every key pressed if there is any unacceptable word.

An example, this array ['insulto1','insulto2','insulto3'] .

How do I check if any of those words exists in what the user is typing?

This is the code

$("#adicionar_coment").keyup(function(e){
    var nome = $("#nome_user").html();
    var code = e.keyCode || e.which;
    var html = $("#adicionar_coment").val();
    var array = [Array a cima dito]
    for(var i = 0; i < array.length; i++){
        if(html.indexOf(array[i]) >= 0){
            erro=1;
        }else{
            erro=0;
        }
    }
});

With the above code, it only gives error when it is equal to the last word of the array.

    
asked by anonymous 12.01.2018 / 22:00

2 answers

2

The problem is that even when it encounters an error, it continues to run, you should stop the execution of the for so error = 1, in addition, you do not need to set the error value = 0 on for, just start the error with zero:

$("#adicionar_coment").keyup(function(e){
    var nome = $("#nome_user").html();
    var code = e.keyCode || e.which;
    var html = $("#adicionar_coment").val();
    var array = [Array a cima dito];
    erro = 0;
    for(var i = 0; i < array.length; i++){
        if(html.indexOf(array[i]) >= 0){
            erro=1;
            break;
        }
    }
});
    
12.01.2018 / 22:18
1

You can also do with Regex

/* Lista de Palavrões */
const curseWords = ["word1", "word2", "word3"];

/* Textarea */
const textarea = document.querySelector("textarea");

/* Captura a lista de palavrões e transforma em regex */
const regex = new RegExp("("+curseWords.join("[^a-zA-Z]|").concat("[^a-zA-Z]")+")", "g");

/* Verifica os palavrões a cada letra digitada */
textarea.addEventListener("keypress", function(event) {
  let word = textarea.value.match(regex);
  if( word ) {
    alert("Não escreva palavrões");
    this.value = this.value.replace(/\b[\w]+.$/, "****** ")
    
    console.log( word.lastIndexOf() );
  }
});

/* Verifica os palavrões quando o usuário colar um conteúdo */
textarea.addEventListener("paste", function(event) {
  event.clipboardData.items[0].getAsString(function(text) {
    var t = text.match(regex);
    
    if (t) {
      t.forEach(function(word) {
        text = text.replace( word, "******* " );
      });

      textarea.value = text;
    }
  });
});
<textarea rows="10" cols="60"></textarea>
    
12.01.2018 / 23:13