find the longest word in a string in typescript

One way to find the longest word in a string in TypeScript is by using the split() method to separate the string into an array of words, then looping through the array to find the word with the longest length.

Here's a TypeScript function that accomplishes this:

index.ts
function findLongestWord(str: string): string {
  let words = str.split(" ");
  let maxLength = 0;
  let longestWord = "";
  
  for (let i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
      longestWord = words[i];
    }
  }
  
  return longestWord;
}
310 chars
15 lines

To use this function, simply call it with a string parameter:

index.ts
let myString = "The quick brown fox jumped over the lazy dog";
let longestWord = findLongestWord(myString);
console.log(longestWord); // "jumped"
146 chars
4 lines

This function works by splitting the input string into an array of words using the space character as the delimiter. It then loops through the array of words, keeping track of the word with the longest length it has found so far. Once it has looped through all the words, it returns the longest word it found.

gistlibby LogSnag