filmov
tv
How to find the longest word in a String with JavaScript
Показать описание
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.
Комментарии