The task was: Find the Longest Word in a String Return the length of the longest word in the provided sentence. Your response should be a number.
and the code:
function findLongestWordLength(str) {
let words = str.split(' ');
let maxLength = 0;
for(let i = 0; i < words.length; i++){
if(words[i].length > maxLength){
maxLength = words[i].length
}
}
return maxLength;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.
In the beginning I just added quotes without space between them and didn't get the right result. And when added space, then I have got the right result, but I don't understand what does mean this space and how did it work? What topic is this?
If you mean the quotes in this line:
let words = str.split(' ');
That's to split by each word in the sentence. If you did this:
let words = str.split('');
You would be splitting by character.
const sentence = "hello there"
console.log(sentence.split(" "));
console.log(sentence.split(""));
str.split() accepts delimeter and return array of strings. delimeter can be any character here.
In this example we are using ' ' and 'fox' to get the array of string.

here you can see sentence broken into two parts before and after fox. So passing empty string '' will not split the sentence since it is not available in the sentence itself.