DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Finding the Longest Word in a String

  • Let's return the length of the longest word in the provided sentence.
  • Also the response should be a number in this instance.
function findLongestWordLength(str) {
  return str.length;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function findLongestWordLength(str) {
  let words = str.split(" ");
  let longest = "";
  for (let i = 0; i < words.length; i ++) {
    let tempLong = words[i];
    if (tempLong.length > longest.length) {
      longest = tempLong;
    }
  }
  return longest.length;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog"); // will display 6
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  • Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.
  • Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.

OR

function findLongestWordLength(str) {
  let words = str.split(" ");
  let longest = "";
  for (let word of words) { // <-----
    if (word.length > longest.length) {
      longest = word;
    }
  }
  return longest.length;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
Enter fullscreen mode Exit fullscreen mode
  • Here instead of the for loop that loops through the indexes we loop through the elements themselves.

Top comments (0)