find the shortest word in a string in typescript

To find the shortest word in a string in TypeScript, you can follow these steps:

  1. Split the string into an array of words
  2. Initialize a variable to store the shortest word, and set its value to the first word in the array
  3. Loop through the array of words
  4. For each word, check if its length is shorter than the current shortest word. If it is, update the shortest word variable
  5. Finally, return the shortest word variable

Here's the TypeScript code:

index.ts
function findShortestWord(str: string): string {
  const words = str.split(" ");
  let shortestWord = words[0];

  for (let i = 1; i < words.length; i++) {
    if (words[i].length < shortestWord.length) {
      shortestWord = words[i];
    }
  }

  return shortestWord;
}
272 chars
13 lines

This function takes a string as input and returns the shortest word in the string. It uses the split method to turn the string into an array of words, loops through the array using a for loop, and checks each word's length to find the shortest one. It then returns the shortest word using the return keyword.

gistlibby LogSnag