skip to Main Content
function findLongestWordLength(str) {
  
  //Creating the regex and adding the solution in the array
  let word = [];
  let regex = /[A-Za-z]+S/g;
  let result = str.match(regex);
  word.push(result);
  
  //Iterating the array using forEach
  let currentWord = 0;
  word.forEach((element) => {
    element.forEach((element2) => {
      let longestWord = element2.length;
      if (currentWord < longestWord) {
        currentWord = longestWord;
      }
    });
  });
  
  //It returns the longest word (the length of that word)
  return currentWord;
}

console.log(
  findLongestWordLength("The quick brown fox jumped over the lazy dogs")
);

This is a good solution but can be this algorithm improved ?

Help me guys out to find a simplify solution

I need feedback about this code I made

Thanks

2

Answers


  1. Just compact and make it more readable and simplify it to this?

    function findLongestWordLength(str) {
        let maxLen = 0;
        str.match(/[A-Za-z]+S/g)?.forEach(s => {
            if (s.length > maxLen) {
              maxLen = s.length;
            }
        });
        return maxLen;
    }
    
    console.log(
      findLongestWordLength("The quick brown fox jumped over the lazy dogs")
    );
    
    console.log(
      findLongestWordLength("")
    );
    Login or Signup to reply.
  2. Slightly shorter, return the longest word:

    const findLongestWord = str => str.split(/W{1,}/)
      .reduce((a, c) => c.length > a.length ? c : a, '');
    
    console.log(findLongestWord(`I am a lonely pilgrim searching 
    for stackoverflowishness in the wildermark.`));
    // => stackoverflowishness
    

    Or if you just want the length of the longest word (your subject says the longest word but your code says the longest word length):

    const findLongestWordLength = str => str.split(/W{1,}/)
      .reduce((a, c) => c.length > a.length ? c : a, '').length;
    
    console.log(findLongestWordLength(`I am a lonely pilgrim searching 
    for stackoverflowishness in the wildermark.`)); // => 20
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search