To find the shortest word in a string in JavaScript, you can use the following function:
index.tsx
functionshortestWord(str) {
// Split the string into an array of wordsconst words = str.split(" ");
// Initialize the shortest word as the first word in the arraylet shortest = words[0];
// Iterate through the array of wordsfor (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 wordif (words[i].length < shortest.length) {
shortest = words[i];
}
}
// Return the shortest wordreturn 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"