find the longest word in a string in javascript

index.tsx
function longestWord(str) {
  // split the string into an array of words
  var words = str.split(" ");
  // variable to store the longest word
  var longest = "";
  
  // loop through each word
  for (var i = 0; i < words.length; i++) {
    // if the current word is longer than the longest word, update longest
    if (words[i].length > longest.length) {
      longest = words[i];
    }
  }
  // return the longest word
  return longest;
}

// Example usage:
var str = "The quick brown fox jumped over the lazy dog";
console.log(longestWord(str)); // Output: "jumped"
569 chars
21 lines

gistlibby LogSnag