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

Asked

Viewed 43 times

1

I am trying to make a language filter where it checks after each key pressed if there is any word not accepted.

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

How do I check if any of those words exist 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.

2 answers

2


The problem is that even when you encounter an error, the is keeps running, you must stop the execution of the is as soon as error = 1, moreover, you do not need to set the value error = 0 no 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;
        }
    }
});
  • Just what I needed! Thank you :)

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>

  • Although your answer is correct, the answer that was accepted fit better in my question, but it is always good to learn other ways

Browser other questions tagged

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