Hi guys, wanted to see what you thought of using regex for this exercise.
function findLongestWordLength(str) {
let longest = 0;
let regex = /\w+/g; // Note: ‘g’ searches a pattern more than once. (Global)
let arr = str.match(regex);
for (let index = 0; index < arr.length; index++) {
if (longest < arr[index].length) {
longest = arr[index].length;
}
}
return longest;
}
let result = findLongestWordLength(“The quick brown fox jumped over the lazy dog”);
console.log(result);
/*
Steps:
-
Set a ‘longest’ varaible to hold the longest string (top of function).
-
Pass all non-whitespace values to an array (use regex and match function).
-
Loop through the array and check each values’ length.
-
Set a condition checking if the current value is larger than the longest String.
-
If the current value is longer, pass that Strings size to ‘longest’ variable.
-
Return ‘longest’.
*/