How to find the longest word in a String with JavaScript

preview_player
Показать описание

This can be useful if you want to pick out or limit the size of words in a string and sometimes gets set as a coding challenge for interviews.

Don’t forget to subscribe to the Junior Developer Central channel for more videos and tutorials!

If you’re looking for some basic algorithm scripting to find the longest word in a string, there’s no easier way than using a sort function on the words in the string.

But first, we need to make sure we have the words of the string set out in an array. To do this, we’ll need to use the split() function to transform our string in to an array of words. We’re going to make an assumption that words are separated by a space in order to split our string up.

In the tutorial to find the longest word in a string, you’ll then see how we can transform our array of words to be re-ordered with the longest length string at the top, or first, in the array. This requires a little bit of understanding as to how the sort function works in JavaScript but essentially giving a positive value the item is moved up the array. The details of the sort function aren’t too important here to find the longest word in a string JavaScript but a general understanding is handy.

Once the sort function has ordered all of the words in our array, we can simply pick off the first item by accessing it a position 0 in the array. As we’ve sorted the words in the array to be largest first this will give us the longest word in our original string in JavaScript.

Just to finish off the tutorial, we’ll see how this process can be put inside a function to enable it to be re-used throughout other parts of your code should you need find longest word in a string javascript elsewhere in your code.

Рекомендации по теме
Комментарии
Автор

This video was so helpful with figuring out an assignment! Thank you!

jennym
Автор

the legend style question solve Thank you for help me!

sharvanpandit
Автор

Great help! Thank you so much, brother!

abirmahmud
Автор

Very good way of thinking, I did it differently but we both got the same results, nice Job

josuegarcia
Автор

Hello so in my course we haven't seen the split method, how would u achieve the same without it? Imanage to split the words making an array of each one but now I'm lost

SrSushii
Автор

I didn't know, how to do it. Thank you

uaplatformacomua
Автор

I love your style. But my question is how can you reverse words with 6 or more letters in a given string. That is 'My second programs code' turn to "My dnoces smargorp". Thank you

ralphdeeney
Автор

how can I find minest word on the string function??

alvemollah