Hi! I think I might have found an alternative solution to this problem. It’s kind of a stupid and inelegant solution but it doesn’t use any concepts that haven’t been introduced yet. It also doesn’t require the use of a regex. The only problem with it is that it doesn’t work on strings ending with some kind of punctuation, which is why a regex solution is probably better. It did work well enough to pass the challenge, but is it considered a valid solution, or just clever enough to pass the tests?
Edit: the console.log stuff is left over from when I was trying to figure out what was wrong with my code before I figured I could just add a space to the end of the string
My code:
function findLongestWordLength(str) {
str += " " // I had to include this because otherwise it wouldn't get the last word
let longest = 0
let current = 0
for (let i = 0; i < str.length; i++) {
if (str[i] == " ") {
if (current > longest) {
longest = current;
console.log(longest)
}
current = 0;
} else {
current++
}
}
return longest
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")
// 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/114.0.0.0 Safari/537.36
Challenge: Basic Algorithm Scripting - Find the Longest Word in a String
Link to the challenge: