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 geeksforgeeks where students learn programming"
Output: "geeksforgeeks"
We can use the following approaches to find the longest word within the string in JavaScript:
Table of Content
- Approach 1: Using regex and for...loop
- Approach 2: Using the split() and sort() method
- Approach 3: Using split() and reduce() methods
- Approach 4: Using split() and for...loop
- Approach 5: Using sort() method
- Approach 6: Using map() and reduce() methods
- Approach 7: Using split() and Array.prototype.every() method
Approach 1: Using regex and for...loop
Here, we use regex to split the string into an array of words by using the regex /[a-zA-Z0-9]+/gi and then using for loop iterate the array and search the largest string.
Example: This example uses the above-explained approach.
// Javascript program to search largest word from a string
function longest(str) {
// Split the string using regex
str = str.match(/[a-zA-Z0-9]+/gi);
// Creating a empty string to store largest word
let largest = "";
// Creating a for...loop to iterate over the array
for (let i = 0; i < str.length; i++) {
// If the i'th item is greater than largest string
// then overwrite the largest string with the i'th value
if (str[i].length > largest.length) {
largest = str[i];
}
}
return largest;
}
console.log(
longest(
"Hello guys this is geeksforgeeks where" +
" students learn programming"
)
);
Output
geeksforgeeks
Approach 2: Using the split() and sort() method
Here, we split the string using the String.split() method and sort the array using the Array.sort() method.
Example: This example uses the above-explained approach.
function longest(str){
// Split the string into array
str = str.split(" ")
// Return the first sorted item of the Array
return str.sort((a, b) => b.length - a.length)[0]
}
console.log(longest("Hello guys this is geeksforgeeks"+
" where students learn programming"))
Output
geeksforgeeks
Approach 3: Using split() and reduce() methods
Here, we will split the string using the String.split() method, and by using the reduce method we search for the largest element of the array, which is your largest string.
Example: This example uses the above-explained approach.
function longest(str) {
// Split the string into array
str = str.split(" ");
// Get the index of largest item of the array
let index = str.reduce((acc, curr, i) => {
if (curr.length > str[acc].length) {
return i;
}
return acc;
}, 0);
return str[index];
}
console.log(
longest(
"Hello guys this is geeksforgeeks" +
" where students learn programming"
)
);
Output
geeksforgeeks
Approach 4: Using split() and for...loop
Here, we will split the string and before that, we will declare an empty string in order to store the resulted from the longest string in it. Also, we will be using an arrow function and this whole task will be performed under it only.
Example: This example uses the above-explained approach.
// JavaScript code to for the above approach..
let longestWord = (string) => {
let stringg = string.split(" ");
let longest = 0;
let longest_word = null;
for (let i = 0; i < stringg.length; i++) {
if (longest < stringg[i].length) {
longest = stringg[i].length;
longest_word = stringg[i];
}
}
return longest_word;
};
console.log(
longestWord(
"Hello guys this is geeksforgeeks where students learn programming"
)
);
Output
geeksforgeeks
Approach 5: Using sort() method
To find the longest word within a string in JavaScript using the sort
method, you can follow these steps:
- Split the string into an array of words.
- Use the
sort
method to sort the array based on the length of each word. - Retrieve the last (or first, depending on the sorting order) element of the sorted array, as it will be the longest word.
Example: Here, the findLongestWord
function takes an input string, splits it into an array of words, sorts the array based on the length of each word in descending order, and then returns the longest word.
function findLongestWord(inputString) {
// Step 1: Split the string into an array of words
const wordsArray = inputString.split(/\s+/);
// Step 2: Sort the array based on word length
const sortedWords = wordsArray.sort(function (a, b) {
return b.length - a.length; // Sort in descending order by word length
});
// Step 3: Retrieve the longest word (first element after sorting)
const longestWord = sortedWords[0];
return longestWord;
}
// Example usage:
const inputString = "JavaScript is an awesome programming language";
const result = findLongestWord(inputString);
console.log("Longest word:", result);
Output
Longest word: programming
Approach 6: Using map() and reduce() methods
In this approach, we split the string into an array of words using the String.split() method. Then, we use the map() method to transform each word into an object containing the word itself and its length. Finally, we use the reduce() method to find the object with the maximum length and return its word.
Example:
function longestWord(str) {
// Split the string into an array of words
const words = str.split(" ");
// Use map() to create an array of objects containing each word and its length
const wordLengths = words.map(word => ({ word, length: word.length }));
// Use reduce() to find the object with the maximum length
const longestWordObj = wordLengths.reduce((prev, current) => {
return (prev.length > current.length) ? prev : current;
});
// Return the word from the object with the maximum length
return longestWordObj.word;
}
console.log(longestWord("Hello guys this is geeksforgeeks where students learn programming"));
Output
geeksforgeeks
Approach 7: Using split() and Array.prototype.every() method
In this approach, we first split the input string into an array of words using the split() method. Then, we use the every() method to iterate through each word and update the longest word if the current word's length is greater than the length of the previously stored longest word.
Example: This example uses the above-explained approach.
function findLongestWord(str) {
// Split the string into an array of words
const words = str.split(" ");
// Initialize a variable to store the longest word
let longestWord = "";
// Use every() method to iterate through the array
words.every(word => {
// If the current word's length is greater than longestWord's length
// update the longestWord
if (word.length > longestWord.length) {
longestWord = word;
}
// Return true to continue the loop
return true;
});
return longestWord;
}
console.log(findLongestWord("Hello guys this is geeksforgeeks where students learn programming"));