DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

1

Finding the longest word in a sentence/string (freecodecampnotes)

In this exercise we are given the following snippet to find the longest word in the sentence.

findLongestWordLength(str) {

   return maxLen
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
Enter fullscreen mode Exit fullscreen mode

Below are our attempts

//Attempt 1
function findLongestWordLength(str) {
let arr=str.split('')
let maxLen=0;
for(let i=0;i<arr.length;i++){
if(arr[i].length>maxLen){
maxLen=arr[i].length
}
}
return maxLen
}
//Attempt 2
function findLongestWordLength(str) {
let arr=str.split(' ')
let maxLen=0;
for(let i=0;i<arr.length;i++){
if(arr[i].length>maxLen){
maxLen=arr[i].length
}
}
return maxLen
}
view raw longest.js hosted with ❤ by GitHub

What is the correct answer? Attempt 2 as always, the reason being..

The split function

Image description

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️