How to find the largest and the smallest word in a string with JavaScript

2 Answers

0 votes
const s = "javascript php python c++ c c# java"
   
let max = "";
let min = s;
    
const words = s.split(" "); 
    
for (let i = 0; i < words.length; i++) {
    if (words[i].length > max.length)
        max = words[i];    
    if (words[i].length < min.length)
        min = words[i];
}
   
console.log("Longest word: " + max);
console.log("Shortest word: " + min);
           
   
/*
   
run:
   
Longest word: javascript
Shortest word: c
   
*/

 



answered Mar 23, 2017 by avibootz
edited Oct 10, 2024 by avibootz
0 votes
/**
 * Finds the largest and smallest words in a given string.
 * 
 * @param {string} text - The input string containing words.
 * @returns {[string, string]} An array containing [largestWord, smallestWord].
 */
function findLargestAndSmallestWords(text) {
    if (!text || text.trim() === '') {
        return ['', ''];
    }

    // Split the string into words using a regular expression for arbitrary whitespace
    const words = text.trim().split(/\s+/);
    
    if (words.length === 0) {
        return ['', ''];
    }

    let largest = words[0];
    let smallest = words[0];

    // Iterate through the words to find extrema based on length
    for (const word of words) {
        if (word.length > largest.length) {
            largest = word;
        }
        if (word.length < smallest.length) {
            smallest = word;
        }
    }

    return [largest, smallest];
}

// Main execution
const s = "JavaScript is a programming language used for web and server-side development";

// Use modern ES6 array destructuring to unpack the returned values cleanly
const [largest, smallest] = findLargestAndSmallestWords(s);

console.log(`Largest word:  ${largest}`);
console.log(`Smallest word: ${smallest}`);


/*
run:

Largest word:  programming
Smallest word: a

*/

 



answered 1 day ago by avibootz
...