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

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

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