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 the longest word
Example
function longest(str) {
var words = str.split(' ');
var longest = 0;
for (var i=0;i<words.length;i++) {
if (words[i].length > longest) {
longest = words[i].length;
}
}
return longest;
}
longest("This is Andela");
//This returns 6
How do i edit this code such that it returns the word instead of the amount of alphabets.That is
//Returns Andela instead of 6
Considering i am also new to javascript
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With