How to find the longest word in a string

Overview

We all know what a string is in JavaScript and how we use it. We can use a string to write a long sentence or even a passage using the back-ticks.

So, in this shot we are going to answer this question: how do we find the longest word in a long string?

Example

Let’s look at the following code and try to understand it.

Note: Don’t worry — the code is followed by an explanation for better understanding of it.

Console
JavaScript - longest word in a string

Explanation

  • Line 1: We create a function. The name of the function is getLongestWord. It has argument named str which represents a string to be passed later when calling the function.

  • Line 2: We define a variable, words. This variable was assigned to the str calling it with the .split() method that turns it into an array.

Note: The .split() method splits a string and all the words become values of an array. It has many separator options, and here we used the ' ', which stands for empty space, meaning that the words will be separated by empty spaces.

  • Line 3: We assign the value 0 to a new variable, maxLength.

  • Line 4: The longestword function becomes a new variable, and nothing is assigned to it.

  • Line 6: We create an iteration, define the variable i was, and assign 0 to it. As long as the value of i is less than the length of words, it increases the value of i automatically.

  • Lines 7–10: We create an if statement. We pass i into word, as long as words[i].length1 (the value in the array) is greater than maxLength, and we will assign the word[i].length to maxLength while word[i] will be assigned to longestWord.

Note: This will check the array of words one by one until it reached the one with the largest length.

  • Line 13: We print the number of words in the longest word when we call the function.

  • Line 14: We print the longest word in the console when we call the us function.

  • Line 18: We call the function.