Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!