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