I know that doing this must be easy, but I really don't know how I could do it, I was working on it and I was investigating but I got stuck. It would help me a lot if someone could help me finish my code. Beforehand thank you very much.
function findLongestWord(str) {
var pp = str.split(" ");
return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
I have already divided the string into an array, the only thing I need is to know how to measure each word individually and know which is the one that measures more. At first I thought of using a for loop to go from word to word but after that I ran out of ideas, please help.
There are several ways to do this:
Another way :
In fact you were doing it correctly and the idea you had was correct, use a loop and compare the length:
How about this way?
http://jsbin.com/xucewaqefo/edit?html,js,output
You break the text into words, loop through them and compare length.
I answered a question that was originally very similar to this one. That question was then edited and changed substantially, so my answer doesn't make any sense there. However, here it could be useful, which is why I share it here:
There is an interesting article with three methods to get the longest word . You can choose the one you prefer.
In the link there are commented code snippets for each method. I've modified it to return the word, if you want it can also return the length.
1. Using loop
for
2. Using
sort()
3. Using
reduce()
It worked for me like this:
This is the shortest way, I think.