Open In App

How to find the longest word within the string in JavaScript ?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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




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

By 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.

Javascript




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.

Javascript




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

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




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

Using sort() method

To find the longest word within a string in JavaScript using the sort method, you can follow these steps:

  1. Split the string into an array of words.
  2. Use the sort method to sort the array based on the length of each word.
  3. 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.

Javascript




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



Previous Article
Next Article

Similar Reads

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" Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks
3 min read
What is the difference between “word-break: break-all” versus “word-wrap: break-word” in CSS ?
The word-break property in CSS is used to specify how a word should be broken or split when reaching the end of a line. The word-wrap property is used to split/break long words and wrap them into the next line. Difference between the "word-break: break-all;" and "word-wrap: break-word;" word-break: break-all; It is used to break the words at any ch
2 min read
Find Word Character in a String with JavaScript RegExp
Regular expressions or RegExp can be used in JavaScript to search for patterns in texts. Searching for a certain character in a string, such as locating all occurrences of a word character, is a typical activity. In this article, we'll look at how to utilize RegExp in JavaScript to find word characters in a string. Terminologies: Regular expression
4 min read
JavaScript Program to Find the Most Frequent Word in a String
In this article, we'll 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 techniques. Example: Input: apple
2 min read
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: had Input: “Ravi had been saying that” Output: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUsing indexOf methodUsing Nested for loopUsing a
3 min read
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 th
4 min read
JavaScript Program to Calculate the Frequency of Each Word in the Given String
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript. Example:Input:"geeks for geeks is for geeks"Output:"geeks": 3 , "for": 2 , "is": 1 Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript: Table of Content Using an Object Using Map Using an Obj
2 min read
JavaScript Program to Extract First Word from a String
In this article, we have to extract the first word from the input string in JavaScript language. Below is an example for better understanding. Examples: Input: Geeks for Geeks Output: Geeks Input: I Love India Output: I Examples of Extracting First Word from a StringTable of Content Using split() MethodUsing substring() and indexOf() MethodsUsing R
4 min read
JavaScript Program Replace Specific Words with Another Word in a String using Regular Expressions
In this article, we are going to learn about replacing specific words with another word in a string using regular expressions. Replacing specific words with another word in a string using regular expressions in JavaScript means searching for all occurrences of a particular word or pattern within the text and substituting them with a different word
3 min read
How to get the function name from within that function using JavaScript ?
Given a function and the task is to get the name of the function from inside the function using JavaScript. There are basically two methods to get the function name from within that function in JavaScript. These are: Using String substr() MethodUsing Function prototype name propertyGet the Function name using String substr() MethodThis method gets
2 min read