Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

find longest word in a string javascript

function longestWord(string){
  let words = string.split(' ');
  let lengthArray = [];
  let maxNumber;
  let largestWord = '';
  
  for(let i = 0; i < words.length; i++){
    lengthArray.push(words[i].length);
  }
  
  maxNumber = Math.max(...lengthArray);
  
  largestWord = words[lengthArray.indexOf(maxNumber)];
  
  return largestWord;
}

let str = "The quick brown fox jumped over the lazy dogs";
let longWord = longestWord(str);

console.log(longWord); //output is jumped
 
PREVIOUS NEXT
Tagged: #find #longest #word #string #javascript
ADD COMMENT
Topic
Name
8+8 =