Find the Longest Word in a String

I’ve decided to use regular expression here, not sure if this is the best idea but I would be glad to hear some advices from you what I could do better here.

function findLongestWordLength(str) {
  let longest = 0;
  let temp = 0;
  let regex = /[A-Za-z]|[-]/;
  for(let i = 0; i < str.length; i++) {
    if(regex.test(str[i])) {
      temp++;
    } else {
      if(temp > longest) {
        longest = temp;
      }
      temp = 0;
    }
  }
  if(temp > longest) {
    longest = temp;
  }
  return longest;
}

Then if we get dot symbol it counts as a letter

I’ve placed my comparison part into true condition and now it works w/o code repetition. Thanks!

function findLongestWordLength(str) {
  let longest = 0;
  let temp = 0;
  let regex = /[A-Za-z]|[-]/;
  for(let i = 0; i < str.length; i++) {
    if(regex.test(str[i])) {
      temp++;
      if(temp > longest) {
        longest = temp;
      }
    } else {
      temp = 0;
    }
  }
  return longest;
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.