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

324
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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