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

320
Views
Find if the sentence has 3 consecutive words

You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string "start 5 one two three 7 end" contains three words in succession.

Input : String Output : Boolean

This is what I'm trying to do, please point out my mistake. Thanks.

function threeWords(text){
    let lst = text.split(' ');
    for (let i=0; i< 3; i++) { 
        if (typeof lst[i] === 'string' &&  Number(lst[i]) === NaN) {return true}
        else {return false;}}
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you'd rather continue with your code than use regex, here are your issues:

  1. You only loop over 3 of the elements in lst. Loop over the entire length of the list.
  2. You try to check if Number('somestring') === NaN. In JavaScript, NaN === NaN is False. Use isNaN() instead.
  3. Once you find a list element that is not a number, you return True. You should have a variable that keeps track of how many words there are in succession (resetting to 0 when you find a number), and return True when this variable is equal to 3.

Here is the fixed code:

function threeWords(text) {
   let lst = text.split(' ');
   let num_words = 0;

   for (let i = 0; i < lst.length; i++) {
      if (isNaN(Number(lst[i])))
         num_words++
      else
         num_words = 0
      
      if (num_words === 3)
         return true 
   }
   return false;
}

about 4 years ago · Juan Pablo Isaza Report

0

Might be easier with a regular expression:

const result = /([A-Za-z]+( |$)){3}/.test('start 5 one two three 7 end');

console.log(result);

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!