# Basic Algorithm Scripting: Find the Longest Word in a String

Hello all,
I have posted my code below and fee the logic is correct (all be it not the most elegant). When I run the code in another environment (brackets) I can get the largest number to console.log but not return. The free code camp site will not even run the code. Any suggestions would be appreciated;

``````function findLongestWordLength(str) {
var counter =0;
var number =[];
var b =0;
for(var i=0; i< str.length; i++)
if(str[i] !== ' '){
counter +=1;
}else{
number[b] = counter;
b++;
counter = 0;
}

var largest = 0

for(var c =0; c <=largest ; c++){
if(number[c] > largest){
largest = number[c];
}

}
return largest;

}
``````

can you post the challenge link this is for?

I think the linter used is having trouble with the fact that your first for loop is not wrapped in { and }.

Once you fix that, your code still has a logic issue for the last test case of

findLongestWordLength(â€śWhat if we try a super-long word such as otorhinolaryngologyâ€ť)

Your solution returns 4, when it should return 19.

Wow thank you !! will keep at it but this helps a ton thanks again!

Use var res = str.split(" "); to get split string at place of every " " and after just count length of every member array.

Itâ€™s not an elegant code, but it definitely works

``````function findLongestWordLength(str) {
let longWord = str.split(' ')[0].length;
for (let i =1; i < str.split(' ').length; i++) {
//Traversing the length of the array
let curWord = str.split(' ')[i].length;
// compare one by one...
if (longWord < curWord ) {
longWord = curWord;
}
}
return longWord;
}
let con = findLongestWordLength("May the force be with you");
console.log(con);
``````
``````function findLongestWordLength(s) {

return s.split(' ').reduce((acc, cur) => {
return Math.max(acc, cur.length);
},0);

}
let con = findLongestWordLength("The quick brown fox jumped over the lazy dog");
console.log(con);
``````

resource - https://youtu.be/UXiYii0Y7Nw

1 Like