How to find the longest word in a string with JavaScript

2 Answers

0 votes
function findLongestWord(s) {
    const words = s.split(' ');
    let longLength = 0;
    let longWord = "";
    const len = words.length;
     
    for (let i = 0; i < len; i++) {
        if (words[i].length > longLength) {
            longLength = words[i].length;
            longWord = words[i];
        }
    }
    
    return longWord;
}

console.log(findLongestWord("JavaScript is ECMAScript specification programming language"));
   


/*
run:

specification

*/

 



answered Sep 16, 2021 by avibootz
edited Mar 2 by avibootz
0 votes
function findLongestWord(s) {
  const words = s.split(/\s+/);
  
  return words.reduce((max, w) => 
    w.length > max.length ? w : max
  , "");
}

console.log(findLongestWord("Could you recommend a good restaurant nearby?"));



/*
run:

restaurant

*/

 



answered Mar 2 by avibootz
...