Quick actions

cmd+k|ctrl+k

Navigation

Languages

Longest Word

Snippet info

Language

JavaScript

Visibility

public

Author

anikeshdey2020

Created

2022-10-12T07:55:32.557999Z

Updated

2022-10-12T09:40:35.219231Z


//function with regex
function LongestWord(sen) { 
  var longestWord = "";
  
  //separate sentence with spaces
  //remove the punctuation with regex
  var arr = sen.replace(/[^\w\s\']|_/g, "").replace(/\s+/g, " ").split(" ");
  var totalItems = arr.length;
  
  //loop over the array
  for(var i = 0; i < totalItems; i++){
    //check if item's length is more than current longest word
    if(arr[i].length > longestWord.length){
      //if it is then set new longest word
      longestWord = arr[i];
    }
  }

  // code goes here  
  return longestWord; 
}

//function without regex 
function LongestWord2(sen) { 
  var longestWord = "";
  
  //total length of sentence
  var totalLength = sen.length;
  var temp = ""
  for(var i= 0; i < totalLength; i++){
      //console.log("char",`${sen[i]} - ${sen[i].charCodeAt()}`);
      //check if character is space or not
      if(sen[i] !== " "){
          if((sen[i].charCodeAt() > 64 && sen[i].charCodeAt() < 91) || (sen[i].charCodeAt() > 96 && sen[i].charCodeAt() < 123)){
              temp += sen[i];
          } else {
              continue;
          }
      } else {
          //console.log("temp:", temp);
          if(temp.length > longestWord.length){
              longestWord = temp;
          }
          
          temp = "";
      }
      
      if(i == totalLength - 1 && temp.length > longestWord.length){
            longestWord = temp;
      }
  }
  
  // code goes here  
  return longestWord; 
}
   
// keep this function call here 
console.log(LongestWord2("fun&!! time"));
INFO