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

135
Visualizações
Find a whole word in a string - Javascript

I want a method that finds a word in a string, it have to be a whole array, not subarray on a string(as array.includes() does)

const key = ['one','two','three']
let message = 'onepiece'

    key.forEach((j) => {
    //string.prototype.includes()
    if(message.includes(j)) console.log('Method1',true); //In this way is true always there is a 'one', no matter if the string is just 'one' or 'onepiece' or 'one piece'
    else  console.log('Method1',false)
    
    //array.prototype.includes()
    if(j.includes(message)) console.log('Method2',true); //In this way is true when message = 'one'
    else  console.log('Method2',false)
});

The following code does what I want

const key = ['one','two','three']
let message = 'one'

    for (var i=0 ; message[i]!=undefined ; i++){
        mes = message.split(" ")[i]
        if(key.includes(mes)) console.log(true) //In this way is true when the message contains 'one', no matter if it's alone or in a string, but false if it's 'onepiece'
    }

I feel this code is highly inefficient, my question is there a simpler way to do this function?

Thx!

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

0

Sounds like you are looking for intersection between two arrays since you are treating messsage as an array by splitting it. In that case you could use array.some() to check if any words in key exist in message:

const key = ['one', 'two', 'three']
let message = 'one'

let mes = message.split(' ')

let result = key.some(val => mes.includes(val))

console.log(result)

//Result is true for 'one'
//Result is true for 'one piece'
//Result is false for 'onepiece'

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