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

172
Visualizações
How can I check if a string contains a phrase or word in JavaScript, but also make sure that the word isn't within another?

I need to check if there is a phrase or a word within a certain string. However, the word can't be within another word. For example, if the string is "Hi, how are you? This is really cool, by the way." If I'm looking for the word "hi", it should only show up once- the one inside the "this" shouldn't be counted. The "how are you" should also be counted since that is a phrase I'm looking for. Below is my code. Essentially, I have an array of arrays with phrases that I'm looking for. I have a += because if the string says "Hi, how are you?" for example, I want to respond to both the "hi" and "how are you." I think I might have to use regular expressions, but I'm not really sure how I would go about doing so. Any guidance would be much appreciated. Thank you so much!

for(let a = 0; a < userquestions.length; a++) {
    for (let b = 0; b < userquestions[a].length; b++) {
        if(usermessage.includes(userquestions[a][b])) {
            responsemessage += chatbotresponses[a][Math.floor(Math.random() * chatbotresponses[a].length)];
        }
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should use regex, indeed.

Try this:

function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|[]\/\])/g, "\\$1");
}

function searchWholeWord(wholeWord, hostString)
{
    var regex = '\\b';
    regex += escapeRegExp(wholeWord);
    regex += '\\b';
    var result = new RegExp(regex, 'i').test(hostString);
    return result
}

found = searchWholeWord("hi", "Hi, how are you? This is really cool, by the way.");
alert(found);
//returns true

found = searchWholeWord("hi", "This is really cool, by the way.");
alert(found);
//returns false

http://jsfiddle.net/Ydr3R/

Based on this post: Search for a whole word in a string

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