Find the Longest Word in a String (with regex)

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:

  1. Set a ‘longest’ varaible to hold the longest string (top of function).

  2. Pass all non-whitespace values to an array (use regex and match function).

  3. Loop through the array and check each values’ length.

  4. Set a condition checking if the current value is larger than the longest String.

  5. If the current value is longer, pass that Strings size to ‘longest’ variable.

  6. Return ‘longest’.

*/

Sounds like a good start if you are a beginner with Regex.