I\'m trying to find the longest word in a string, but it continually returns the length of the first word. Any ideas?
Here\'s my code:
function findL
I would do something like this:
function longestWord(str){
return str.match(/\w+/g).reduce((p,c) => p.length > c.length ? p.length:c.length);
}
function findLongestWord(str) {
//This is what I used to find how many characters were in the largest word
return str
.replace(/[^\w ]/g,'')
.split(' ')
.sort(function(a, b) {return a.length-b.length;})
.pop().length;
}
findLongestWord('The quick brown fox jumped over the lazy dog');
Your return statement is in the wrong place, as mccainz said, however you should also be saving the word if you want to return the actual word.
function findLongestWord(str) {
var words = str.split(' ');
var longestLength = 0;
var longestWord;
for (var i=0;i<words.length;i++) {
if (words[i].length > longestLength) {
longestLength = words[i].length;
longestWord = words[i];
}
}
return longestWord;
}
Here's a functional approach:
function findLongestWord(str) {
return str
.replace(/[^\w ]/g,'') //remove punctuation
.split(' ') //create array
.sort(function(a, b) {return a.length-b.length;}) //sort in order of word length
.pop(); //pop the last element
}
console.log(findLongestWord('For the next 60s, we will be conducting a test.')); //conducting