JavaScript Program to find Smallest and Largest Word in a String
Last Updated :
17 Jun, 2024
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 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 =
"GeeksforGeeks is a computer science portal.";
let result = myFunction(inputStr);
console.log(result);
Output{ smallest: 'a', largest: 'GeeksforGeeks' }
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 =
"GeeksforGeeks is a computer science portal.";
let result = myFunction(inputStr);
console.log(result);
Output{ smallest: 'a', largest: 'GeeksforGeeks' }
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 = "GeeksforGeeks a computer science portal.";
let result = myFunction(inputStr);
console.log(result);
Output{ smallest: 'a', largest: 'GeeksforGeeks' }
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"
OutputSmallest word: a
Largest word: sample
Using the sort() Method
In this approach, we will split the string into words, sort them based on their lengths, and then pick the first and last elements of the sorted array as the smallest and largest words respectively.
Example:
JavaScript
function myFunction(str) {
let words = str.match(/\b\w+\b/g); // Correctly extract words using match() with the regular expression
if (!words || words.length === 0) {
return { smallest: "", largest: "" };
}
words.sort((a, b) => a.length - b.length);
let smallest = words[0];
let largest = words[words.length - 1];
return { smallest, largest };
}
let inputStr = "GeeksforGeeks is a computer science portal.";
let result = myFunction(inputStr);
console.log(result); // Output: { smallest: 'a', largest: 'GeeksforGeeks' }
Output{ smallest: 'a', largest: 'GeeksforGeeks' }
Time Complexity: O(n log n), where n is the number of words in the input string due to the sorting operation.
Space Complexity: O(k), where k is the number of words in the input string, since the array of words is stored in memory.
Similar Reads
Java Program to Print Smallest and Biggest Possible Palindrome Word in a Given String A Palindrome String is a string whose reversed string is equal to the original string. In this Java Program, we are going to see the approach of printing the smallest and biggest palindrome word in a String. Given a sentence of words in the form of a string, and we need to print the smallest and lon
3 min read
Java Program to Search a Particular Word in a String Using Regex In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a
3 min read
Java Program to Find the Most Repeated Word in a Text File Map and Map.Entry interface will be used as the Map interface maps unique keys to values. A key is an object that is used to retrieve a value at a later date. The Map.Entry interface enables you to work with a map entry. Also, we will use the HashMap class to store items in "key/valueâ pairs and acc
3 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching Given a set of strings, find the longest common prefix. Examples:Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- âgeeksforgeeksâ and âgeeksâ. What is the longest common prefix in
3 min read
How to find the longest word within the string in JavaScript ? To find the longest word within the string in JavaScript we will compare the counts to determine which word has the most characters and return the length of the longest word. Example: Input: "This is a demo String find the largest word from it"Output: "largest"Input: "Hello guys this is geeksforgeek
6 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program to Find Occurrence of a Word Using Regex Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
How to Find the Longest Common Prefix of Two Strings in Java? In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: âgeeâ Input: String 1= flower, String 2 = flightOutput: âflâ Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by whi
4 min read
How to find the last index using regex of a particular word in a String? To find the last index of a particular word in a string using regular expressions in Java, you can use the Matcher class along with a regular expression that captures the desired word. Java Program to last index Using the Regex of a Particular Word in a StringBelow is the implementation of the last
2 min read
How to Split a String into Equal Length Substrings in Java? In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list.Example:In the
3 min read