Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda