Tell us what’s happening:
The .length on index is not working inside the loop.
Is that normal?
Your code so far
function findLongestWordLength(str) {
let theRegex = /\S+/g;
let newStr = str.match(theRegex);
console.log(newStr);
let strLength=[];
for(let i =0; i <=str.length; i++){
console.log(i);
strLength = str[i].length;
}
return str.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
.
Challenge: Find the Longest Word in a String
Link to the challenge:
Learn to code. Build projects. Earn certifications.Since 2015, 40,000 graduates have gotten jobs at tech companies including Google, Apple, Amazon, and Microsoft.
what do you see to say that it doesn’t work?
TypeError: Cannot read property ‘length’ of undefined
instead of console.log(i)
try to do console.log(str[i])
- do you see the expected values?
that’s working, but i need the length of items inside the array.
this line is not working :
`strLength = str[i].length;
TypeError: Cannot read property ‘length’ of undefined
the length of str[i]
is always 1
what’s your array? are you sure you are iterating over it?
Yes there is an edit.
Check this line:
for(let i =0; i <=newStr.length; i++){
console.log(i)
strLength = newStr[i].length;
}
newStr is the array created by the regex;
Like this:
[ ‘The’,
‘quick’,
‘brown’,
‘fox’,
‘jumped’,
‘over’,
‘the’,
‘lazy’,
‘dog’ ]
and console.log(i) gives the 0-9(the number of words)
so i need the length of each word by newStr[index].length
newStr[i].length
but the while consoling the newStr[i].length give
TypeError: Cannot read property ‘length’ of undefined
now try again with console.log(newStr[i])
inside the loop, do you have the values you expect?
not the strings, i need string length
ilenia
July 9, 2020, 3:33pm
10
please do this check and look at what appears in the console
i done that. It gives the words. I wish to get 3 on the first word " The " while console.log(newStr[0].length);
ilenia
July 9, 2020, 3:42pm
12
try inside the loop
console.log(newStr[i])
console.log(newStr[i].length)
and look at where the error appear
console.log(newStr[0].length) works out side the loop perfectly.
but that not showing any results inside the loop.
ilenia
July 9, 2020, 3:45pm
14
what’s your current code?
what’s appearing in the console?
Yes now its working Thank you
i <= str.length
your last loop access to str[i]
is undefined, so you get that error.
1 Like
Yea looks good I dont know y it doesn’t work