Find longest string help

First, I know I can probably do this with built in functions, but I wanted to try this way first… The challenge is “Find the Longest Word in a String”

The code works sometimes… But there’s something wrong and I cannot find what… Can someone help?

function findLongestWord(str) {
	//transformar em array
	//a cada espaço, recomeçar a contar
	//comparar com contagem da palavra anterior
	var array = str.split('');
	var thisWord = 0;
	var longest = 0;
	for(var i=0; i<array.length-1;i++){
		if(array[i] == " "){
			if(thisWord > longest){
				longest = thisWord;
			thisWord = 0;
	return longest;

var ret = findLongestWord("Fui no tororo");


If you pass a single space in to split, you’ll get individual words instead of letters.

var string = "I like pie";
string.split(' '); // ["I", "like", "pie"]
1 Like

notice that the ‘if’ statement is only doing something if it runs into a blank space. And inside that if statement is the longestWord comparison/reset…

That is all well and fine, but what happens when the ‘longest word’ is the last word in the string?

1 Like