Please let me know what is wrong with this code:
I know there are much simpler ways to achieve the desired result, however I want to understand how to make this specific code run, and what are my errors. Try to change as little as possible about it, or else let me know why this could not work. Also note that I am trying to console.log 3 values, not just one. Thank you.
EDIT: Here's the freeCodeCamp exercise against which I'm actually testing if the code works: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string For some reason most answers work in the snippet in here, but not in the freeCodeCamp exercise console?
function findLongestWordLength(str) {
let arr = [];
let longestWord = "";
let longestNum = 0;
/*If there is a character at str[i] add it to the arr, else if there is whitespace
don't add it to the arr. Instead, find the arr.length, if is greater than the
previous overwrite longestNum, longestWord and empty the
arr, if not just empty the arr and keep going*/
for (let i = 0; i <= str.length - 1; i++) {
if (/./i.test(str[i])) {
arr.push(str[i]);
} else if (/\s/.test(str[i])) {
if (arr.length - 1 >= longestNum) {
longestNum = arr.length - 1;
longestWord = arr.join("");
arr = [];
} else {
longestNum = longestNum;
longestWord = longestWord;
arr = [];
}
}
}
console.log(arr);
console.log(longestWord);
console.log(longestNum);
return longestNum;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
if (/./i.test(str[i])) {is testing any char, are you looking for a full stop, then you need \. - if you are looking for any alphabetical char you want [a-zA-Z0-9]longestNum = longestNum; longestWord = longestWord;