function longestWord(string) {
var str = string.split(\" \");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
function longestWord(sentence){
var arr = sentence.match(/[a-z]+/gi);
arr.sort(function(a, b){
return b.length - a.length;
});
return arr[0];
}
longestWord('hello man@#$%');
// ==> output: hello
The index is going up to str.length -1
:
for (var i = 0; i < str.length - 1; i++) {
So the last word is not processed.
Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice")
. You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA
).
In case you're in doubt, the simplest way to fix it is removing the -1
from the for
loop.
for (var i = 0; i < str.length; i++) {
Check a demo with both versions (the problematic and the fixed): link here.
You have a -1
in your condition, it never even scans it:
for (var i = 0; i < str.length - 1; i++) {
Should be:
for (var i = 0; i < str.length; i++) {
Demo: http://jsfiddle.net/LfgFk/
function LongestWord(sen) {
// code goes here
const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
wordsArray.sort((a, b) => a.length < b.length);
return wordsArray[0];
}
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i=0; i < str.length-1; i++) {
word = longest < str[i].length ? str[i].length : longest;
word = str[i];
}
return word;
}
longestWord('I love Python ')
solutions are incomplete. what if there r 2 or more words that have same length. here is a better solution:
longest = str => {
let words = str.split(" ");
let size = 0;
let max = [""];
for (let i = 0; i < words.length; i++) {
if (words[i].length > size) {
size = words[i].length;
}
if (max[max.length - 1].length < words[i].length) {
max = [];
max.push(words[i]);
} else {
max = [...max, words[i]];
}
}
return max;
};