Currently trying to figure out how to find the longest word in as string and my research has gotten me somewhere. I found a code on SO that shows the amount of alphabets in
I recommend this approach:
function LongestWord(text) {
return text
.split(/\s+/)
.reduce(function (record, word) {
if (word.length > record.length)
record = word;
return record;
}, '');
}
console.log(LongestWord('It is obvious which is the longest word.'));
If you want to return the length of the longest word, just add .length to the end of the return.
There you go:
function longest(str) {
var words = str.split(' ');
var longest = ''; // changed
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) { // changed
longest = words[i]; // changed
}
}
return longest;
}
console.log(longest("This is Andela"));
I think the easiest solution is to split, sort the array by length and then pick the first element of the array.
function longest(str) {
var arr = str.split(" ");
var sorted = arr.sort(function (a,b) {return b.length > a.length;});
return sorted[0];
}
If you want the length, just add .length to return sorted[0].