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 First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 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 Second Most Repeated Word in a Sequence
Finding the second most repeated word in a sequence involves analyzing a given text or sequence of words to determine which word appears with the second-highest frequency. This task often arises in natural language processing and text analysis. To solve it, we need to parse the input sequence, count
5 min read
JavaScript Program to Sort Strings in Alphabetical Order Ignoring Case
In this article, we are given an array of strings, you need to sort the given array of strings containing both uppercase and lowercase characters in ascending order by ignoring the case in JavaScript. Example 1: Input :- arr = ["Geeks", "for", "geeks", "is", "The", "Best"] Output :- [ 'Best', 'for',
3 min read
JavaScript Program to Find Shortest Distance Between Two Words in an Array of Words
Given an array of words and two target words, the task is to find the shortest distance (minimum number of words) between the two target words in the array. The distance is calculated by counting the number of words between the two target words, excluding the target words themselves. Approaches to f
2 min read
JavaScript Program to Find Words which are Greater than given Length k
In JavaScript, to find words that are greater than the given length k, we need to split an array into words and then filter out words based on their lengths. Table of Content Using split and filter methodsUsing forEach and an empty arrayUsing RegEx Using split and filter methodsIn this approach, we
2 min read
JavaScript - Find Second Largest Element in an Array
Here are the different approaches to find the second largest element in an arary using JavaScript. 1. Using SortingSort the array in ascending order. Iterate from the end of the sorted array to find the first element that is different from the largest. If no such element is found, return null, indic
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 t
3 min read
JavaScript Program to Find Lexicographically Next String
In this article, we are going to learn about Lexicographically next string in JavaScript. A lexicographically next string is the immediate string in a sorted order that comes after a given string when considering character sequences. It's determined by rearranging characters to find the smallest cha
3 min read
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a",
3 min read