How to use String.prototype.match() and Math functions In Javascript

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




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

Similar Reads

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....

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....

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....

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....