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.
Explanation
-
Line 1: We create a function. The name of the function is
getLongestWord. It hasargumentnamedstrwhich represents a string to be passed later when calling the function. -
Line 2: We define a variable,
words. This variable was assigned to thestrcalling 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
0to a new variable,maxLength. -
Line 4: The
longestwordfunction becomes a new variable, and nothing is assigned to it. -
Line 6: We create an iteration, define the variable
iwas, and assign0to it. As long as the value ofiis less than the length ofwords, it increases the value ofiautomatically. -
Lines 7–10: We create an
ifstatement. We passiintoword, as long aswords[i].length1(the value in the array) is greater thanmaxLength, and we will assign theword[i].lengthtomaxLengthwhileword[i]will be assigned tolongestWord.
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
usfunction. -
Line 18: We call the function.