Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SerhiiLihus/188b131d97c87401affe to your computer and use it in GitHub Desktop.
Save SerhiiLihus/188b131d97c87401affe to your computer and use it in GitHub Desktop.
Find the Longest Word in a String separated with spaces(only)
// Bonfire: Find the Longest Word in a String separated with spaces(only)
// Author: @serhiilihus
// Challenge: http://www.freecodecamp.com/challenges/bonfire-find-the-longest-word-in-a-string?solution=function%20findLongestWord(str)%20%7B%0A%20%20str%20%2B%3D%20%22%20%22%3B%0A%20%20var%20maxLength%20%3D%200%3B%0A%20%20while%20(%20str.indexOf(%22%20%22)%20%3E%200%20)%20%7B%0A%20%20%20%20%20%0A%20%20%20%20%20%20str%20%3D%20str.substr(str.indexOf(%22%20%22)%2B1%2Cstr.length)%3B%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20if%20(%20str.indexOf(%22%20%22)%20%3E%20maxLength%20)%0A%20%20%20%20%20%20%20%20%20%20maxLength%20%3D%20str.indexOf(%22%20%22)%3B%0A%20%20%7D%20%20%0A%20%20return%20maxLength%3B%0A%7D%0A%0AfindLongestWord(%22The%20quick%20brown%20fox%20jumped%20over%20the%20lazy%20dog%22)%3B%0A
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function findLongestWord(str) {
str += " ";
var maxLength = 0;
while ( str.indexOf(" ") > 0 ) {
str = str.substr(str.indexOf(" ")+1,str.length);
if ( str.indexOf(" ") > maxLength )
maxLength = str.indexOf(" ");
}
return maxLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment