find the shortest word in a string in javascript

To find the shortest word in a string in JavaScript, you can use the following function:

index.tsx
function shortestWord(str) {
  // Split the string into an array of words
  const words = str.split(" ");
  
  // Initialize the shortest word as the first word in the array
  let shortest = words[0];
  
  // Iterate through the array of words
  for (let i = 1; i < words.length; i++) {
    // If the current word is shorter than the shortest word,
    // update the shortest word to be the current word
    if (words[i].length < shortest.length) {
      shortest = words[i];
    }
  }
  
  // Return the shortest word
  return shortest;
}
540 chars
20 lines

Here's an example of using this function:

index.tsx
const str = "The quick brown fox jumps over the lazy dog";
const shortest = shortestWord(str);
console.log(shortest); // Output: "The"
135 chars
4 lines

gistlibby LogSnag