How to usesplit() and for…loop in Javascript

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 w3wiki where students learn programming"
    )
);

Output
w3wiki

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 w3wiki where students learn programming"
Output: "w3wiki"

We can use the following approaches to find the longest word within the string in JavaScript:

Table of Content

  • Using regex and for…loop
  • By using the split() and sort() method
  • Using split() and reduce() methods
  • Using split() and for…loop
  • Using sort() method

Similar Reads

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

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

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

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

Approach 5: Using sort() method

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

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