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
JavaScript Program to Find the Most Frequent Word in a String
We will explore a couple of approaches to finding the most frequent word in a string and provide clear explanations along with practical examples. Determining the most frequent word in a string is a common task in text analysis and processing. In JavaScript, we can accomplish this task using various
5 min read
JavaScript Program to Find Longest Common Substring Between Two Strings
In this article, we will see how to find the longest common substring between two strings in JavaScript. A substring is a contiguous sequence of characters within a string. It can be obtained by extracting part of the string starting from any position. We are going to write a JavaScript function tha
4 min read
JavaScript Program to find Lexicographically next String
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order.Examples: Input : testOutput : tesuExplanation : The last character 't' is changed to
3 min read
JavaScript Program to Compare Two Strings Lexicographically
This JavaScript program compares two strings lexicographically, meaning it checks if one string comes before or after the other in alphabetical order. Lexicographical comparison is based on the Unicode value of each character in the strings. The program should return a positive value if the first st
2 min read
JavaScript Program for Printing Shortest Common Supersequence
A Shortest Common Supersequence (SCS) is the shortest or smallest string that contains two given strings as a subsequence. It is a minimal combination of characters that includes all elements of both input strings. In this article, we will see different approaches for printing the shortest common su
8 min read
JavaScript Program to Find kth Largest/Smallest Element in an Array
JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array. There are
5 min read
JavaScript Program to find the Nth smallest/largest element from an unsorted Array
In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It rep
4 min read
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 Remove a Given Word From a String
Given a string and a word that task to remove the word from the string if it exists otherwise return -1 as an output. For more clarity go through the illustration given below as follows. Illustration: Input : This is the Geeks For Geeks word="the" Output : This is Geeks For Geeks Input : Hello world
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