I'm creating a custom function that will identify and extract the longest word from a given string. If there are multiple words of the same length, the function will return the first one it encounters. The function also disregards numbers and punctuation marks during this process. Here's how the function works:
function findLongestWord(inputString){
var wordLengths = [];
var result = "";
window.onload = function(){
inputString = inputString.replace(/[^a-z " "]/gi, ''); // Remove non-alphabetic characters
inputString = inputString.split(" ");
for (var i = 0; i < inputString.length; i++){
wordLengths[i] = parseInt(inputString[i].length);
}
wordLengths = wordLengths.sort();
for (var j = 0; j < inputString.length; j++){
if(parseInt(inputString[j].length) == Math.max(...wordLengths)){
result = inputString[j];
break;
}
}
}
return result;
}
The issue I've encountered is that the function currently returns the data type ("string") instead of the actual value.