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

417
Vistas
Finding longest word in a string javascript code that is not working on the last wordd

I've already solved this by using a split function but I'm still confused as to why my previous for-loop only code is not working when I'm trying to find the longest word in a string in javascript. The function I'm writing is supposed to return the number of letters of the longest word. After using the console, whenever i use only one word, it returns the value i initialized the counter of the letters with (which is 0). If the longest word is the last word, it returns the second longest word on the preceding words. If the longest word is on anywhere except the last word, the result is accurate. It seems like it has trouble counting the letters of the last word. Here is my code.

let lettCount = 0;
let largest = 0;
let spaceCheck = /\s/;

for(let i = 0; i < str.length; i++) {

  if(spaceCheck.test(str[i]) == true) {
    if(lettCount > largest) {
      largest = lettCount;
    }
    lettCount = 0;
  } else {
    lettCount++;
  }

}

return largest;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should be able to simplify the logic here significantly, using String.split() and Math.max().

We split the string into an array, then use Array.map() to get the length of each word, then use Math.max() along with the Spread syntax to get the longest word.

let str = 'the longest word is dinosaur';

function getLongest(str) {
    return Math.max(...str.split(/\s/).map(s => s.length));
}

console.log('Longest word:', getLongest(str));

You can also do this with String.split() and Array.reduce(), this is even a little simpler:

let str = 'the longest word is dinosaur';

function getLongest(str) {
    return str.split(/\s/).reduce((acc,s) => s.length > acc ? s.length: acc, 0);
}

console.log('Longest word:', getLongest(str));

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