JavaScript Program to find Smallest and Largest Word in a String

We are going to discuss how can we find the Smallest and Largest word in a string. The word in a string which will have a smaller length will be the smallest word in a string and the word that has the highest length among all the words present in a given string will be the Largest word in a string.

There are a few approaches by which we can find the Smallest and Largest word in a string:

  • Using Regular Expression
  • Using reduce method
  • Using for loop

Using Regular Expressions

In this approach, we are using \w+ regex pattern, “str.match()“extracts words from the input string. We then use the map() method to find the smallest and largest words by comparing their lengths and we will Return an object containing these words.

Example: In this example, The myFunction JavaScript function takes a string input, extracts individual words, and finds the smallest and largest words based on their lengths. It uses regular expressions to match words, initializes variables for the smallest and largest words, and iterates through the words to update these variables.

Javascript
function myFunction(str) {
    const words = str.match(/\b\w+\b/g);
    if (!words) return { smallest: "", largest: "" };

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

    words.map(word => {
        if (word.length < smallest.length) {
            smallest = word;
        }
        if (word.length > largest.length) {
            largest = word;
        }
    });

    return { smallest, largest };
}

let inputStr = 
    "w3wiki is a computer science portal.";
let result = myFunction(inputStr);
console.log(result);

Output
{ smallest: 'a', largest: 'w3wiki' }

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(k), where k is the number of words in the input string.

Using reduce() method

In this approach, we are using reduce() method, we will split the string into words by using split() method then we will initialize smallest and largest variabel having the first word as a value then iterate through the whole string and updating them based on length comparisons. And at last return the smallest and largest words.

Example: This example shows the use of the above-explained approach.

Javascript
function myFunction(str) {
    let words = str.split(' ');

    if (words.length === 0) {
        return { smallest: "", largest: "" };
    }
    let smallest = words.reduce((a, b) =>
        (a.length <= b.length ? a : b));
    let largest = words.reduce((a, b) =>
        (a.length >= b.length ? a : b));


    return { smallest, largest };
}

let inputStr =
    "w3wiki is a computer science portal.";
let result = myFunction(inputStr);
console.log(result);

Output
{ smallest: 'a', largest: 'w3wiki' }

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(k), where k is the number of words in the input string.

Using for loop

In this approach, The myFunction JavaScript function splits the input string into words, initializes variables for the smallest and largest word, and iterates through the words to find the smallest and largest word among them . At last or end of iteration It returns an object containing the smallest and largest words.

Example: This example shows the use of the above-explained approach.

Javascript
function myFunction(str) {
    let words = str.split(' ');
    if (words.length === 0) {
        return { smallest: "", largest: "" };
    }
    
    let smallest = words[0];
    let largest = words[0];
    
    for (let i = 1; i < words.length; i++) {
        let word = words[i];
        if (word.length < smallest.length) {
            smallest = word;
        }
        if (word.length > largest.length) {
            largest = word;
        }
    }
    return { smallest, largest };
}

let inputStr = "w3wiki a computer science portal.";
let result = myFunction(inputStr);
console.log(result);

Output
{ smallest: 'a', largest: 'w3wiki' }

Time Complexity: O(n), where n is the number of words in the input string.

Space Complexity: O(1), as the function maintains only a constant amount of extra space regardless of the input size.

Using String.prototype.match() and Math functions

Using String.prototype.match() with a regular expression extracts words. Then, Math functions find the lengths of the smallest and largest words. Finally, find() retrieves the words with these lengths.

Example:

JavaScript
function findSmallestAndLargestWord(str) {
    const words = str.match(/\w+/g) || []; // Extract words using match() and regex
    const smallest = Math.min(...words.map(word => word.length)); // Find smallest word length
    const largest = Math.max(...words.map(word => word.length)); // Find largest word length
    const smallestWord = words.find(word => word.length === smallest); // Find smallest word
    const largestWord = words.find(word => word.length === largest); // Find largest word
    return { smallest: smallestWord, largest: largestWord }; // Return smallest and largest words
}


const result = findSmallestAndLargestWord("This is a sample string");
console.log("Smallest word:", result.smallest); // Output: "a"
console.log("Largest word:", result.largest);   // Output: "string"

Output
Smallest word: a
Largest word: sample