Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
javascript check if string contains words in array and replace them

I'm having trouble trying to check a string for words from an array and if it includes the word replace them.

var blocked = [
  "inappropriate word one",
  "inappropriate word two",
];

var message = "the message has an inappropriate word one";

if (blocked.some(string => message.includes(string))) {
  message = message.replace(string, "blocked")
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In the body of the if the variable string is not available anymore because it's only valid in the callback of some. So just loop over the blocked words and do the replacement.

blocked.forEach(string => {
  if (message.includes(string)) message = message.replace(string, "blocked");
})

In principle the check isn't necessary. If the search value is not contained in the string, nothing will be replaced, so you can just do the following:

blocked.forEach(string => {
  message = message.replace(string, "blocked");
})

But be aware that String::replace(search, replacement) only replaces the first occurence of search if it is a string. So if your "badword" occurs more than once, only the first occurence will be replaced. So it might be better to define your blocked words as regex, because this way you can replace multiple occurrences.

var replacements = [
  /badwordone/gi, 
  /badwordtwo/gi
]

replacements.forEach(r => { 
  message = message.replace(r, "blocked");
})
about 4 years ago · Juan Pablo Isaza Relatório

0

You are using message.replace(string), but string isn't defined outside the scope of that some() method. It is only available inside the some() method and is not available outside. Therefore your code doesn't work.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda